K. M
K. M

Reputation: 917

How do I query a list of entities in a many to many relationship in JPA?

Suppose I have the following two entities:

@Entity
@Table(name="manifest")
public class Manifest extends DbTable implements Serializable {
    public Manifest() { }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long id;

    @ManyToMany(cascade=CascadeType.ALL, mappedBy="manifests",fetch= FetchType.LAZY)
    public List<Thingy> thingys;
}

and

@Entity
@Table(name="thingy")
public class Thingy extends DbTable implements Serializable {
    public Thingy(){}

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long id;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "manifest_thingy",
            joinColumns = @JoinColumn(name = "thingy_id", referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name = "manifest_id", referencedColumnName="id"))
    public List<Manifest> manifests;
}

How can I query my thingies that belong to a given manifest? I have tried queries like

"SELECT DISTINCT d 
 FROM Thingy d
 WHERE :manifest MEMBER OF d.manifests"

or

"SELECT DISTINCT d
 FROM Thingy d
 JOIN d.manifests m
 WHERE m = :manifest"

or

"SELECT DISTINCT d
 FROM Thingy d
 JOIN d.manifests m
 WHERE m.id = :manifestId"

the latter of those three being basically the only suggestion I could find searching around for this, but to no avail. For all 3 of those I think what I'm getting is an empty list (rather than an error). The query is being fed through something like this (parameters set as appropriate):

myEntityManager
    .createQuery(giantQueryStringGoesHere, Thingy.class)
    .setParameter("manifest", myManifestObject)
    .getResultList();

Upvotes: 0

Views: 45

Answers (1)

Nicholas Hirras
Nicholas Hirras

Reputation: 2596

If you know the specific manifest ID couldn't you just retrieve that manifest and get the list of thingys from it?

Manifest m = em.find(Manifest.class, manifestId);
List<Thingy> thingys = m.thingys;

Upvotes: 1

Related Questions