如何在JPA中查询多对多关系中的实体列表?

时间:2017-11-16 00:42:44

标签: java hibernate jpa

假设我有以下两个实体:

@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;
}

@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;
}

如何查询属于给定清单的物品?我尝试了像

这样的查询
"SELECT DISTINCT d 
 FROM Thingy d
 WHERE :manifest MEMBER OF d.manifests"

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

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

这三者中的后者基本上是我能找到的唯一建议,但无济于事。对于所有这3个人,我认为我得到的是一个空列表(而不是错误)。查询正在通过类似的方式提供(参数设置为适当的):

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

1 个答案:

答案 0 :(得分:1)

如果你知道特定的清单ID,你只是检索那个清单并从中获取东西列表?

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