2

I defined a many-to-many relation between two entities with a composite key. The problem is that when I get the join object it is filtered with only one side of the relation and not both side.

The picture makes the problem clearer. Here what im looking for is dtid=185 and prid=352 but what I get from many-to-many relation is two highlighted rows.

enter image description here

Entiry D:

@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "d", orphanRemoval = true)
private List<DP> dp = new ArrayList<DP>();

Entity P:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "p")
private List<DP> dp = new ArrayList<DP>();

PK class:

public class DPPK implements Serializable{

   private Integer d;

   private Integer p;
}

Join:

@IdClass(DPPK.class)
@Entity
@Table(name = "definition_property")
@NamedQueries({
    @NamedQuery(name = "DP.findAll", query = "SELECT d FROM DP d")})
public class DefinitionProperty extends AbstractEntity{

    @Id
    @JoinColumn(name = "dtid", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private D d;
    @Id
    @JoinColumn(name = "prid", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private P p;

    @Column(name = "initial_value")
    @Basic(optional = false)
    private String initialValue;
gabi
  • 1,324
  • 4
  • 22
  • 47
  • You didn't show the query used to try to obtain the DP with dtid=185 and prid=352. It should just be a matter of em.find(new DPPK(185, 532)). What you've shown isn't a ManyToMany relation, it is two separate 1:M relations. If you are traversing the list from one end, you need to do your own search within that 1:M list for the DP instance that you are looking for. – Chris Sep 17 '15 at 12:28

1 Answers1

0

Try using Embedded Ids for defining the Composite Key and then try filtering out the required values. Here is a previous query from StackOverflow which details how to use Embedded Ids - How to create and handle composite primary key in JPA

Community
  • 1
  • 1
Dhruv Rai Puri
  • 1,335
  • 11
  • 20