如何解决如何使用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
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。