Hibernate subquery detachedCriteria
Asked Answered
P

2

8

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='[email protected]'))

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

Pokey answered 25/10, 2012 at 19:0 Comment(0)
S
7

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)));
Stanwood answered 25/10, 2012 at 19:8 Comment(3)
Sounds like it didn't work. If you can provide some more details, perhaps the code you tried, maybe we can help more.Stanwood
Well, your example doesn't actually replicate his code. He has a subquery inside a subquery but yours is just an OR.Uhf
This question asks how to do it with DetachedCriteria. Your answer shows how to do it with Criteria. This is different and doesn't exactly answer the question.Lindalindahl
L
0

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) );
Lindalindahl answered 30/4, 2018 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.