Pan Pan - 2 months ago 6x
Java Question

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


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("", "Iz%") )

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