单向一对多关系的条件查询 [英] Criteria query for unidirectional one-to-many relationship
问题描述
所以,我有以下实体:
@Entity
public class Supplier {
@Column(name = "SUPPLIERID")
private BigInteger supplierId;
@OneToMany
@JoinColumn(name = "ID_SUPP", foreignKey = @ForeignKey(name = "fk_POIS_SUPP"))
private List<POS> posList;
...
}
@Entity
public class POS {
@Column(name = "POSID")
private BigInteger posId
}
因此,POS
没有对Supplier
的引用,这意味着我们具有单向一对多关系.我需要通过posId
和supplierId
查找POS
.即,找到具有指定supplierId
的供应商,然后在具有指定posId的pos的供应商列表中找到一个pos.如何为此编写条件查询?
So, POS
does not have a reference to Supplier
, which means that we have a unidirectional one-to-many relationship. I need to look for a POS
by posId
and supplierId
. That is, find a supplier with the specified supplierId
and then find a pos in the supplier's list of pos's that has the specified posId. How do I write a criteria query for this?
我尝试使用子查询.我的想法是创建一个子查询,该子查询将使用给定的supplierId
获取Supplier
的所有POS
.然后主查询将在这些POS
内搜索具有给定posId
的POS
.
I tried using subqueries. My idea was to create a subquery that would fetch all POS
's of a Supplier
with a given supplierId
. Then the main query would search within those POS
's for a POS
with the given posId
.
问题是我无法编写查询来获取POS
的Supplier
列表.显然您不能编写List<POS>
类型的查询:
The problem was I couldn't write a query that would fetch a Supplier
s list of POS
s. Apparently you can't write a query of type List<POS>
:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<POS> outerQuery = cb.createQuery(POS.class);
Root<POS> outerQueryRoot = outerQuery.from(POS.class);
Subquery<POS> subquery = outerQuery.subquery(POS.class);
Root<Supplier> subqueryRoot = subquery.from(Supplier.class);
subquery.where(cb.equal(subqueryRoot.get(Supplier_.supplierId), supplierId));
subquery.select(subqueryRoot.get(Supplier_.posList);
在最后一行,我得到一个编译错误Expression<POS> does not match Expression<List<POS>>
.而且我无法更改子查询的类型,因为Java不允许通用类文字(List<POS>.class
).
On this last line, I get a compilation error that Expression<POS> does not match Expression<List<POS>>
. And I can't change the type of the subquery because Java doesn't allow generic class literals (List<POS>.class
).
有什么想法吗?
推荐答案
我终于找到了答案,只用了两个roots
:
I finally found the answer, just use two roots
:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<POS> cq = cb.createQuery(POS.class);
Root<POS> posRoot = cq.from(POS.class);
Root<Supplier> supplierRoot = cq.from(Supplier.class);
cq.where(cb.and(
cb.equal(supplierRoot.get(Supplier_.suppliertId), supplierId),
cb.equal(posRoot.get(POS_.posId), posId)));
cq.select(posRoot);
这篇关于单向一对多关系的条件查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!