如何使用CriteriaQuery获取相交查询?

问题描述

给出:

@Entity
public class entity_details  {

@Id
private int id;

@column(name ="entity_id")
private int entityId;

@column(name="att_id")
private int attId;

@column(name="att_value")
private string attVal;

我想找到与以下查询等效的查询

从entity_details中选择object_id,其中att_id = 15和att_value ='test'
相交
从entity_details中选择entity_id,其中att_id = 18和att_value ='test2';

仅使用CriteriaQuery。

解决方法

这是一个复杂的操作,您可以尝试执行以下操作:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);

Root<EntityDetails> root = cq.from(EntityDetails.class);

Subquery<EntityDetails> sq = cq.subquery(EntityDetails.class);
Root<EntityDetails> rootSQ = cq.from(EntityDetails.class);

sq.where(
    cb.and(
        cb.and(
            cb.equal(rootSQ.get("attId"),18),cb.equal(rootSQ.get("attValue"),"test2")
        ),cb.equal(rootSQ.get("id"),root.get("id"))
    )
);

cq.where(
    cb.and(
        cb.and(
            cb.equal(root.get("attId"),15),cb.equal(root.get("attValue"),"test")
        ),cb.exist(sq)
    )
);

cq.multiselect(root.get("entityId"));

什么会生成以下查询:

select e1.entity_id from entity_details e1
where e1.att_id = 15 and e1.att_value = "test"
    and exists(
        select * from entity_details e2
        where e2.att_id = 18 and e2.att_value = "test2"
            and e1.id = e2.id
    )