Hibernate subquery detachedCriteria

人盡茶涼 提交于 2019-12-21 10:32:10

问题


How to write a subquery in hibernate which is having multiple subqueries. for example

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'))

I know that we can write through DetachedCriteria but couldnot find any example where I can use multiple subqueries.


回答1:


Here's an example:

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)));

For multiple subqueries, you can use a boolean operator like 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)));



回答2:


To do it entirely with Detached Criteria (because I like to construct the detached criteria without a session)

DetachedCriteria idQuery = DetachedCriteria.forClass(MyPersistedObject.class)
    .setProjection(Property.forName("id"))
DetachedCriteria recordQuery = DetachedCriteria.forClass(MyPersistedObject.class)
    .add(Property.forName("id").eq(idQuery) );


来源:https://stackoverflow.com/questions/13075390/hibernate-subquery-detachedcriteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!