单向一对多关系的条件查询 [英] Criteria query for unidirectional one-to-many relationship

查看:299
本文介绍了单向一对多关系的条件查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下实体:

@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的引用,这意味着我们具有单向一对多关系.我需要通过posIdsupplierId查找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内搜索具有给定posIdPOS.

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.

问题是我无法编写查询来获取POSSupplier列表.显然您不能编写List<POS>类型的查询:

The problem was I couldn't write a query that would fetch a Suppliers list of POSs. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆