java 休眠条件:向 Restrictions.isEmpty 添加额外限制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10549478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate Criteria: adding additional restriction to Restrictions.isEmpty
提问by simon
I have created a Hibernate (3.5) Criteria query:
我创建了一个 Hibernate (3.5) Criteria 查询:
Criteria criteria = db.getSession().createCriteria(Vendor.class);
criteria.add(Restrictions.isEmpty("models"));
When executed with Criteria.list, Hibernate produces the following SQL (simplified for sake of readability):
当使用 Criteria.list 执行时,Hibernate 生成以下 SQL(为了可读性而简化):
SELECT this_.*
FROM VENDOR this_
left outer join MODEL models1_
ON this_.id = models1_.VENDOR_ID
WHERE NOT EXISTS (SELECT 1
FROM MODEL
WHERE this_.id = VENDOR_ID)
What I'd like to do is add a restriction within the "not exists" part so that the SQL query would look like this
我想要做的是在“不存在”部分添加一个限制,以便 SQL 查询看起来像这样
SELECT this_.* FROM VENDOR this_
left outer join MODEL models1_
ON this_.id = models1_.VENDOR_ID
WHERE
NOT EXISTS (SELECT 1
FROM MODEL
WHERE this_.id = VENDOR_ID AND DEPRECATED = 0 )
Is that possible using the Hibernate Criteria API and if yes, how? Or is there some other possibility to achieve the same result (but still using Criteria API)?
是否可以使用 Hibernate Criteria API,如果是,如何使用?或者是否有其他可能实现相同的结果(但仍然使用 Criteria API)?
回答by JB Nizet
Yes, it's possible, using a subquery:
是的,可以使用子查询:
Criteria criteria = db.getSession().createCriteria(Vendor.class, "vendor");
DetachedCriteria dc = DetachedCriteria.forClass(Vendor.class, "vendor2");
dc.createAlias("vendor2.models", "model");
dc.add(Restrictions.eq("model.deprecated", 0));
dc.add(Restrictions.eqProperty("vendor2.id", "vendor.id"));
dc.setProjection(Projections.id());
criteria.add(Subqueries.notExists(dc));
which is the equivalent of the following HQL query:
这相当于以下 HQL 查询:
select vendor from Vendor vendor
where not exists(select vendor2.id from Vendor vendor2
inner join vendor2.models model
where model.deprecated = 0
and vendor2.id = vendor.id)