如何在具有多个子查询的hibernate中编写子查询。例如
select * from project_dtls where project_id in
(select project_id from project_users where user_id =
(select user_id from user_dtls where email='abc@email.com'))
我知道我们可以通过DetachedCriteria编写,但找不到可以使用多个子查询的任何示例。
答案 0 :(得分:7)
以下是一个例子:
DetachedCriteria exampleSubquery = DetachedCriteria.forClass(MyPersistedObject.class)
.setProjection(Property.forName("id"))
// plus any other criteria...
;
Criteria criteria = getSession().createCriteria(ARelatedPersistedObject.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Subqueries.propertyIn("myPersistedObjectId", exampleSubquery)));
对于多个子查询,可以使用类似Restrictions.or()的布尔运算符:
DetachedCriteria anotherSubquery = DetachedCriteria.forClass(MyPersistedObject.class)
.setProjection(Property.forName("id"))
// plus any other criteria...
;
Criteria criteria = getSession().createCriteria(ARelatedPersistedObject.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.or(
Subqueries.propertyIn("myPersistedObjectId", exampleSubquery),
Subqueries.propertyIn("myPersistedObjectId", anotherSubquery)));
答案 1 :(得分:0)
完全使用Detached Criteria(因为我喜欢在没有会话的情况下构建分离的条件)
DetachedCriteria idQuery = DetachedCriteria.forClass(MyPersistedObject.class)
.setProjection(Property.forName("id"))
DetachedCriteria recordQuery = DetachedCriteria.forClass(MyPersistedObject.class)
.add(Property.forName("id").eq(idQuery) );