How do I create criteria in a field that can be null?

I need to create a Criterion or Criterion in a specific field of myProperity (in the MyClass class ). I have to select all objects that have prop = null or meet certain criteria . So I have to do something like:

Criteria criteria = this.sessionManager.getCurrentSession().createCriteria(MyClass.class);

specificCriteria = criteria.createCriteria('myProperity');
/* definition of specificCriteria */

Disjunction disjunction = Restrictions.disjunction();



The problem is caused by the facts:

  • I cannot add the Criteria for the disjunction (only the Criteria can be added to the Disjunction), so the line: disjunction.add (specificCriteria); wrong
  • I cannot somehow change the spec to accept null because I cannot make the criteria to be null. (This gives me a NullPointerException)

Do you have any idea how to deal with this?


source to share

3 answers

You can get the answer to all questions here it will help you

for ex if your MyClass is like

class MyClass{
   private long id;
   private String myProperity;
   setter & getter


here you fix the problem and it will be related to other criteria.

Criteria criteria = session.createCriteria(MyClass.class);

Disjunction disjunction = Restrictions.disjunction();


criteria.add(Restrictions.eq("id", value));




Just for someone else with this question. I had a similar problem when I wanted to check if the associated collection was empty and if it is not limited to an ID. I was helped for this (updated code for newer version of hibernate):

Criteria criteria = getSession().createCriteria(StaffMember.class);
criteria.createAlias("franchises", "franchises", JoinType.LEFT_OUTER_JOIN)
      "", allowedFranchises)));


Thus, it allows:

  • employees without a franchise
  • employees who are in the franchise with an identifier from the allowedFranchises collection.


Something like this helped me:

final Criteria c = session.createCriteria(House.class)
    // Houses may not have doors.
    .createAlias("door", "door", CriteriaSpecification.LEFT_JOIN)
    // Door may be null, but if it isn't it must be blue.
    .add(Restrictions.or(Restrictions.isNull("door"), Restrictions.eq("door.color", "blue")));


This answer helped me: / ...



All Articles