简体   繁体   中英

Hibernate criteria restriction on multiple criterias

I am writing a Criteria query. My query is on multiple criterias corresponding to tables property and user. It returns the result if prop is 12 or 13 no matter who the user is OR if prop is NULL then user must be loggedInUser. The Sql query has where condition as follows which returns 4 rows

where (property.PROP in (12,13) or (property.PROP is null
                 and user.loggedInUser = 'XYZ'))

My criteria

Criteria userQuery = session.createCriteria(User.class);
Criteria propertyQuery = userQuery .createCriteria("property");

  Criterion crt = (Criterion) userQuery.add(Restrictions.eq("loggedInUser", userId));

propertyQuery.add(
            Restrictions.or( 
                 Restrictions.in("prop",propList),
                    Restrictions.and(Restrictions.isNull("prop"),crt)
                            )
                 );

My issue is that Restrictions.and(criterion,criterion) takes two criterion as parameter. However, the second criterion 'crt' on userQuery is not valid when type casted (Criterion). Hibernate will give error. How can I achieve this functionality in Criteria. or how to write criteria Restrictions.and(Restrictions.isNull("prop") , userQuery.add(Restrictions.eq("loggedInUser", userId)))

Use Joins using hibernate criteria as below example code:

 List cats = session.createCriteria(Cat.class)
     .createAlias("kittens", "kit")
     .add( Restrictions.like("kit.name", "Iz%") )
     .list();

Note: The code above is just an example of how to use Join in hibernate criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM