Hibernate Criteria Queries

The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query

Environment

  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:

Create the following table in mysql
image
Insert the records as follows
image

Step 3:

In the Eclipse, Select File –> New –> Java Project and give Project Name as HibernateCriteria
Click Next –> Go to Libraries Tab-> Click External Jar Files and include the following jar files
  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.1.Final.jar
  • hibernate-entitymanager-4.1.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.18-bin.jar

Step 4:

Create the Employee POJO Class as follows
image
  1:  package mypack;
 
   3:  import javax.persistence.Entity;
   4:  import javax.persistence.GeneratedValue;
   5:  import javax.persistence.Id;
   6:  import javax.persistence.Table;
   7:  import javax.persistence.Column;
   8:   
   9:   
  10:  @Entity
  11:  @Table(name="employee")
  12:  public class Employee {
  13:      private int id;
  14:      private String firstName;
  15:      private String lastName;
  16:      private int salary;
  17:      private int IsActive;
  18:   
  19:      public Employee() {
  20:      }
  21:   
  22:      public Employee(String fname, String lname, int salary) {
  23:          this.firstName = fname;
  24:          this.lastName = lname;
  25:          this.salary = salary;
  26:      }
  27:   
  28:      @Id
  29:      @GeneratedValue
  30:      @Column(name="ID")
  31:      public int getId() {
  32:          return id;
  33:      }
  34:   
  35:      public void setId(int id) {
  36:          this.id = id;
  37:      }
  38:   
  39:      @Column(name="firstName")
  40:      public String getFirstName() {
  41:          return firstName;
  42:      }
  43:   
  44:      public void setFirstName(String first_name) {
  45:          this.firstName = first_name;
  46:      }
  47:   
  48:      @Column(name="lastName")
  49:      public String getLastName() {
  50:          return lastName;
  51:      }
  52:   
  53:      public void setLastName(String last_name) {
  54:          this.lastName = last_name;
  55:      }
  56:   
  57:      @Column(name="salary")
  58:      public int getSalary() {
  59:          return salary;
  60:      }
  61:   
  62:      public void setSalary(int salary) {
  63:          this.salary = salary;
  64:      }
  65:      
  66:      @Column(name="IsActive")
  67:      public int getIsActive() {
  68:          return IsActive;
  69:      }
  70:   
  71:      public void setIsActive(int IsActive) {
  72:          this.IsActive = IsActive;
  73:      }
  74:   
  75:  }
 

Step 5:


Let us create Hibernate Configuration file hibernate.cfg.xml




   1: <?xml version="1.0" encoding="utf-8"?>
   2: <!DOCTYPE hibernate-configuration PUBLIC
   3:  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
   4:  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
   5: <hibernate-configuration>
   6:     <session-factory>
   7:         <!-- Database connection settings -->
   8:         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
   9:         <property name="connection.url">jdbc:mysql://localhost/sampledb</property>
  10:         <property name="connection.username">root</property>
  11:         <property name="connection.password">123</property>
  12:  
  13:         <!-- JDBC connection pool (use the built-in) -->
  14:         <property name="connection.pool_size">1</property>
  15:  
  16:         <!-- SQL dialect -->
  17:         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  18:  
  19:         <!-- Enable Hibernate's automatic session context management -->
  20:         <property name="current_session_context_class">thread</property>
  21:  
  22:         <!-- Disable the second-level cache -->
  23:         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  24:  
  25:         <!-- Echo all executed SQL to stdout -->
  26:         <property name="show_sql">true</property>
  27:  
  28:         <!-- Drop and re-create the database schema on startup -->
  29:         <property name="hbm2ddl.auto">update</property>
  30:  
  31:         <!-- Mapping Classes -->
  32:         <mapping class="mypack.Employee" />
  33:  
  34:     </session-factory>
  35: </hibernate-configuration>

Take care to change the DB Name, User name and Password according to your setup


Step 6:




Next we will create our Test.java in which we are going to test different Hibernate Criteria Queries

image

Here is the Code





   1: package mypack;
   2:  
   3: import java.util.List;
   4: import org.hibernate.Criteria;
   5: import org.hibernate.Query;
   6: import org.hibernate.Session;
   7: import org.hibernate.SessionFactory;
   8: import org.hibernate.Transaction;
   9: import org.hibernate.cfg.Configuration;
  10: import org.hibernate.service.ServiceRegistry;
  11: import org.hibernate.service.ServiceRegistryBuilder;
  12: import org.hibernate.HibernateException;
  13:  
  14: public class Test {
  15:  
  16:     private static SessionFactory factory;
  17:     private static ServiceRegistry serviceRegistry;
  18:  
  19:     public static void main(String[] args) {
  20:         getAllRecords();
  21:     }
  22:  
  23:     public static void getAllRecords() {
  24:         try {
  25:             Configuration configuration = new Configuration();
  26:             configuration.configure();
  27:             serviceRegistry = new ServiceRegistryBuilder().applySettings(
  28:                     configuration.getProperties()).buildServiceRegistry();
  29:             factory = configuration.buildSessionFactory(serviceRegistry);
  30:         } catch (Throwable ex) {
  31:             System.err.println("Failed to create sessionFactory object." + ex);
  32:             throw new ExceptionInInitializerError(ex);
  33:         }
  34:         System.out.println("**Example : Hibernate  SessionFactory**");
  35:         System.out.println("----------------------------------------");
  36:         Session session = factory.openSession();
  37:         Transaction tx = null;
  38:         try {
  39:             tx = session.beginTransaction();
  40:             Criteria cr = session.createCriteria(Employee.class);
  41:             List results = cr.list();
  42:             for (int i = 0; i < results.size(); i++) {
  43:                 Employee emp = (Employee) results.get(i);
  44:                 System.out.println(emp.getFirstName());
  45:             }
  46:             tx.commit();
  47:         } catch (HibernateException e) {
  48:             if (tx != null)
  49:                 tx.rollback();
  50:             e.printStackTrace();
  51:         } finally {
  52:             session.close();
  53:         }
  54:     }
  55: }


Step 7:




Now let us run the Test.Java as Java Application

In the console,  did you see the following errorSad smile 

----------------------------------------
Hibernate: select this_.ID as ID0_0_, this_.firstName as firstName0_0_, this_.IsActive as IsActive0_0_, this_.lastName as lastName0_0_, this_.salary as salary0_0_ from employee this_
org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of mypack.Employee.isActive





If one declares these int,bit,char as Primitive data types in POJO classes.. then we cannot do getter/setter NULL value into this attributes.. but on you these values will allow NULL to store.. so to avoid this conflicts its always suggestible to use WRAPPER classes itself not Primitive types.
So, We would need to initialize these variable with WRAPPER classes only
like int - "Integer"
bit - "Boolean"
char - "Character"




So we will change our POJO Class, because we have two columns where null value are stored and that has been declared as int. So let us change to integer.

Here is the code





   1: package mypack;
   2: import javax.persistence.Entity;
   3: import javax.persistence.GeneratedValue;
   4: import javax.persistence.Id;
   5: import javax.persistence.Table;
   6: import javax.persistence.Column;
   7:  
   8: @Entity
   9: @Table(name="employee")
  10: public class Employee {
  11:     private int id;
  12:     private String firstName;
  13:     private String lastName;
  14:     private Integer salary;
  15:     private Integer IsActive;
  16:  
  17:     public Employee() {
  18:     }
  19:  
  20:     public Employee(String fname, String lname, int salary) {
  21:         this.firstName = fname;
  22:         this.lastName = lname;
  23:         this.salary = salary;
  24:     }
  25:     @Id
  26:     @GeneratedValue
  27:     @Column(name="ID")
  28:     public int getId() {
  29:         return id;
  30:     }
  31:  
  32:     public void setId(int id) {
  33:         this.id = id;
  34:     }
  35:  
  36:     @Column(name="firstName")
  37:     public String getFirstName() {
  38:         return firstName;
  39:     }
  40:  
  41:     public void setFirstName(String first_name) {
  42:         this.firstName = first_name;
  43:     }
  44:  
  45:     @Column(name="lastName")
  46:     public String getLastName() {
  47:         return lastName;
  48:     }
  49:  
  50:     public void setLastName(String last_name) {
  51:         this.lastName = last_name;
  52:     }
  53:  
  54:     @Column(name="salary")
  55:     public Integer getSalary() {
  56:         return salary;
  57:     }
  58:  
  59:     public void setSalary(Integer salary) {
  60:         this.salary = salary;
  61:     }
  62:     
  63:     @Column(name="IsActive")
  64:     public Integer getIsActive() {
  65:         return IsActive;
  66:     }
  67:  
  68:     public void setIsActive(Integer IsActive) {
  69:         this.IsActive = IsActive;
  70:     }
  71: }

Now let us again run the Test.Java as Java Application

Wow!!!! Smile, Output as follows
**Example : Hibernate  SessionFactory**
----------------------------------------
Hibernate: select this_.ID as ID0_0_, this_.firstName as firstName0_0_, this_.IsActive as IsActive0_0_, this_.lastName as lastName0_0_, this_.salary as salary0_0_ from employee this_
John
Robert
Richard
Anderson
Lee
Nelson




Step 8:




Now let us see how we can retrieve all the Active Employee.

image


Here Anderson is active. And also let us consider if that column contains null value, then we will treat that also Active Employees.Here is the Criteria





   1: Criteria cr = session.createCriteria(Employee.class);
   2:             Criterion cr1 = Restrictions.eq("isActive", 1);
   3:             Criterion cr2 = Restrictions.isNull("isActive");
   4:             // To get records matching with OR condistions
   5:             LogicalExpression orExp = Restrictions.or(cr1, cr2);
   6:             cr.add( orExp );
   7:             List results = cr.list();
Assume that we need only Inactive Employee. So as per the records, there are two employee (b’0’)

Criteria cr = session.createCriteria(Employee.class);
        cr.add(Restrictions.eq("isActive", 0));
        List results = cr.list();