NULL and NOT NULL comparison in the Hibernate API

null and not null check

While checking for the null and not null values in the Hibernate API, we have to be careful and there is chance for misunderstanding. This tips explains how to compare the null values in the Hibernate query.

also read:

In Java language, if object==null will return the proper value if it is null or not. That means null==null will returns true in the programming. But, the same scenario is differenet in the database world. if you check for null==null in the query, it will retrun false. That is why database provide a “IS NULL” keyword to check the null values. Hibernate provides equaivalent methods to check the null values. Look into the following example code for more details:

JavaBeatHibernateExample.java

package javabeat.net.hibernate;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Expression;

/**
 * source : www.javabeat.net
 */
public class JavaBeatHibernateExample {
    public static void main(String args[]) {
        Configuration configuration = new Configuration();
        // configuring hibernate
        SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Criteria criteria = session.createCriteria(Student.class);
        criteria.add(Expression.isNotNull("name"));
        List<Student> list = criteria.list();
        for (Student student : list){
            System.out.println(student.getName());
        }
    }
}

In the above code,Expression.isNotNull(“name”) is used for checking the particular colimn for the null values. All the non null rows will be returned for the above code. In the same way you can check for the null values like this:Expression.isNull(“name”)

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. you can find some details in the below link,”http://javadomain.in/hibernate-select-null-value/”

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better