简体   繁体   中英

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();

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM