【发布时间】:2015-04-19 08:07:59
【问题描述】:
我有两个实体:Acknowledgement 和 Industry。前者与后者具有多对多关联,反之亦然。
@Entity
public class Acknowledgement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@ManyToMany
@JoinTable(name = "acknowledgement_industry", joinColumns = @JoinColumn(name = "acknowledgement_id"), inverseJoinColumns = @JoinColumn(name = "industry_id"))
private Set<Industry> industries = new HashSet<>();
}
@Entity
public class Industry {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@ManyToMany(mappedBy = "industries")
private Set<Acknowledgement> acknowledgements = new HashSet<>();
}
我正在尝试创建一个 JPQL/HQL 查询,该查询根据一组 ID 查找确认,这些 ID 还与一组行业 ID 相关联 - 并使用聚合函数 count。所以我想知道有多少确认满足这些标准。以下是我尝试过的一些方法:
long result = (long) this.getEntityManager()
.createQuery(jpql)
.setParameter("acknowledgements", new HashSet<>(acknowledgementIds))
.setParameter("industries", new HashSet<>(industryIds))
.getSingleResult();
参数是整数集。我也尝试过使用实体对象。对于jpql 字符串,我尝试了以下查询(以及一些变体)。
查询 #1
select count(a) from Acknowledgement a where a.id in :acknowledgements and a.industries in :industries
结果
org.postgresql.util.PSQLException: No value specified for parameter 2.
查询 #2
select count(a) from Acknowledgement a where a.id in :acknowledgements and a.industries.id in :industries
结果
org.hibernate.QueryException: illegal attempt to dereference collection [acknowledg0_.id.industries] with element property reference [id]
这种方法适用于其他一些关联类型,但显然不适用于集合。
问题在于industries 关联的IN 子句。我可以编写本机查询,但我想避免这种情况。如何找到 A 类型的实体,这些实体具有关联的 B 类型的对象,其 ID 在给定集中?
我希望我说清楚了。谢谢。
【问题讨论】: