Hibernate Criteria for “in subselect”

前端 未结 3 1089
深忆病人
深忆病人 2020-12-09 19:58

I\'m trying to do something like this, but using Criteria instead of HQL:

select user from User where user in (
    select user fro         


        
相关标签:
3条回答
  • 2020-12-09 20:18

    In clauses usualy can be transformed into join. Tyr this:

    Criteria c = session.createCriteria(User.class, "u");
    c.createAlias("u.userDomain", "ud"); // inner join by default
    c.add(Restrictions.le("ud.id", 1));
    
    0 讨论(0)
  • 2020-12-09 20:20

    The subquery is very useful in cases, that you need to search the User, having one-to-many UserDomains. In that case, the WHERE UserId IN (subquery) brings big advanatage: we are still working with a flat User table/entity... so we can do the proper paging.

    Here is the documentation 15.8. Detached queries and subqueries

    The draft could be: subquery:

    DetachedCriteria userSubquery = DetachedCriteria.forClass(UserDomain.class, "ud")
        // Filter the Subquery
        .add(Restrictions.eq(UserDomain.DOMAIN, domain))
        // SELECT The User Id  
        .setProjection( Projections.property("ud.userId") );
    

    And the main query:

    Criteria query = session.createCriteria(User.class, "u")
        .add( Subqueries.propertyIn("u.id", userSubquery) );
    

    Now we have a query, which could be used for paging

    0 讨论(0)
  • 2020-12-09 20:41

    I finally found it. Turns out it wasn't so hard after all... once you know!

    criteria = criteria.createCriteria(User.USER_DOMAINS).add(Restrictions.eq(UserDomain.DOMAIN, domain));
    

    Yep, there is was, staring me right in the face in the Javadoc: http://www.dil.univ-mrs.fr/~massat/docs/hibernate-3.1/api/org/hibernate/Criteria.html

    0 讨论(0)
提交回复
热议问题