使用休眠DetachedCriteria的子查询中的子查询

时间:2018-09-21 06:07:21

标签: java hibernate hibernate-criteria detachedcriteria

我需要使用Hibernate执行以下sql查询:

select * from Entity1 where Entity1.entity2 in 
(select id from Entity2 where Entity2.entity3 in 
(select id from Entity3 where Entity3.isImportant))

为此可能需要一个DetachedCriteria。因此,我尝试使用它,但是在另一个DetachedCriteria错误内运行子查询。

Criteria cr = getSession().createCriteria(Entity1.class);
cr.createAlias("entity2", "e2");

DetachedCriteria entity2SubQuery = 
DetachedCriteria.forClass(Entity2.class, "entity2"); 
entity2SubQuery.setProjection(Projections.distinct(property("entity2.id")));

DetachedCriteria entity3SubQuery = DetachedCriteria.forClass(Entity3.class, "entity3");
entity3SubQuery.setProjection(Projections.distinct(property("entity3.id")));

entity2SubQuery.add(Subqueries.propertyIn("entity2.entity3", entity3SubQuery));
cr.add(Subqueries.propertyIn("e2.id", entity2SubQuery));

return cr;

在此附上例外情况

- Exception 
java.lang.NullPointerException: null
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getProjectedTypes(CriteriaQueryTranslator.java:382)
at org.hibernate.criterion.SubqueryExpression.createAndSetInnerQuery(SubqueryExpression.java:135)
at org.hibernate.criterion.SubqueryExpression.getTypedValues(SubqueryExpression.java:96)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getQueryParameters(CriteriaQueryTranslator.java:329)
at org.hibernate.criterion.SubqueryExpression.createAndSetInnerQuery(SubqueryExpression.java:134)
...

谢谢

0 个答案:

没有答案