Wednesday, 1 May 2013

Hibernate Criteria Examples


Hibernate Criteria Queries

An easiest way to represent object oriented queries in Hibernate is criteria API. It’s a powerful and refined alternative to Hibernate Query Language (HQL). Criteria API are well suited for creating dynamic search queries. This API is well adapted for creating multi-criteria search functionalities. The search functionalities where queries needs to build “on-the-fly”; there we can use Criteria API. Criteria queries are better for structuring/configuring dynamic queries where a lot of actions are determined at runtime.

Disadvantages of Using Criteria Queries:-
  • Maintenance:-
While using Criteria API, we have to maintain queries in Java side and it is scattered everywhere in java, so if any problem occurs it is very difficult to search and identify. But if we are maintaining queries in Hibernate Mapping file then debugging is very easy.
  • Performance:-
The Criteria API queries are building by Hibernate and we are not capable to optimize and fine tune those queries in case if queries are performing slowly. Whenever we fire a query using Criteria API, it creates a new alias for the table name which does not reflect in the last queries cached by DB. So this way is increasing the burden/overhead of compiling the generated SQL.

Hibernate Criteria Queries Examples:-

Steps for creating example to call a stored procedure using Hibernate:-
  • At first, create a java project using eclipse.
  • Inside src folder, create a package named com.gaurav.hibernate.beans.
  • After that, create a java bean file named Student and place the below corresponding code in that file.
  • Now inside src folder, create hibernate.cfg.xml file and place the below corresponding source code.
  • Now again in the src folder, create Student.hbm.xml file and place the below corresponding source code.
  •  Now in src folder, create a package com.gaurav.hibernate.criteria and place the CriteriaUsingHibernate.java client program in that package which is available below.

Student.java

package com.gaurav.hibernate.beans;

import java.sql.Date;

public class Student {
    private int studentId;
    private String firstName;
    private String lastName;
    private Date birthDate;
    private int totalMarks;
    private String division;

    /**
     * @return the studentId
     */
    public int getStudentId() {
        return studentId;
    }

    /**
     * @param studentId
     *            the studentId to set
     */
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName
     *            the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName
     *            the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the birthDate
     */
    public Date getBirthDate() {
        return birthDate;
    }

    /**
     * @param birthDate
     *            the birthDate to set
     */
    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    /**
     * @return the totalMarks
     */
    public int getTotalMarks() {
        return totalMarks;
    }

    /**
     * @param totalMarks
     *            the totalMarks to set
     */
    public void setTotalMarks(int totalMarks) {
        this.totalMarks = totalMarks;
    }

    /**
     * @return the division
     */
    public String getDivision() {
        return division;
    }

    /**
     * @param division
     *            the division to set
     */
    public void setDivision(String division) {
        this.division = division;
    }

}
hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping resource="Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Student.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.gaurav.hibernate.beans.Student" table="Student">
        <id name="studentId" column="STUDENT_ID" type="int">
            <generator class="assigned" />
        </id>
        <property name="firstName" column="FIRSTNAME" />
        <property name="lastName" column="LASTNAME" />
        <property name="birthDate" column="BIRTHDATE" />
        <property name="totalMarks" column="TOTAL_MARKS" />
        <property name="division" column="DIVISION" />

    </class>
   </hibernate-mapping>

CriteriaUsingHibernate.java

package com.gaurav.hibernate.criteria;

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.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.gaurav.hibernate.beans.Student;

public class CriteriaUsingHibernate {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {

        Session session = null;

        try {

            SessionFactory sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
            session = sessionFactory.openSession();
            Criteria criteria1 = session.createCriteria(Student.class);
            // The division & totalMarks property belongs to Student class.
            /**
             * To get the records whose division is FIRST and whose totalMarks
             * is in between 900-1000.
             */

            criteria1.add(Restrictions.eq("division", "FIRST"));
            criteria1.add(Restrictions.between("totalMarks", 900, 1000));

            List resultsList1 = criteria1.list();
            System.out
                    .println("********** USE OF EQUAL AND BETWEEN EXPRESSION USING CRITERIA API IN HIBERNATE **********");
            System.out
                    .println("################################################################################");
            System.out.println("FIRSTNAME" + "\t LASTNAME" + "\t BIRTHDATE"
                    + "\t TOTAL MARKS" + "\t DIVISION");

            for (int i = 0; i < resultsList1.size(); i++) {
                Student student = (Student) resultsList1.get(i);

                System.out.println("\n");
                System.out.print(student.getFirstName());
                System.out.print("\t\t" + student.getLastName());
                System.out.print("\t\t" + student.getBirthDate());
                System.out.print("\t\t" + student.getTotalMarks());
                System.out.print("\t\t" + student.getDivision());

            }
            System.out.println("\n\n");
            Criteria criteria2 = session.createCriteria(Student.class);

            /**
             * To get the records whose totalMarks is greater than 850 and less
             * than 980 and whose firstName starts with Hem.
             */


            criteria2.add(Restrictions.gt("totalMarks", 850));
            criteria2.add(Restrictions.lt("totalMarks", 980));
            criteria2.add(Restrictions.like("firstName", "Hem%"));

            List<Student> resultsList2 = criteria2.list();

            System.out.println("\n");
            System.out
                    .println("********** USE OF GREATER THAN, LESS THAN AND LIKE EXPRESSION USING CRITERIA API IN HIBERNATE **********");
            System.out
                    .println("##################################################################################");
            System.out.println("FIRSTNAME" + "\t LASTNAME" + "\t BIRTHDATE"
                    + "\t TOTAL MARKS" + "\t DIVISION");

            for (Student student : resultsList2) {

                System.out.println("\n");
                System.out.print(student.getFirstName());
                System.out.print("\t\t" + student.getLastName());
                System.out.print("\t\t" + student.getBirthDate());
                System.out.print("\t\t" + student.getTotalMarks());
                System.out.print("\t" + student.getDivision());
            }

            System.out.println("\n\n");
            Criteria criteria3 = session.createCriteria(Student.class);

            Criterion total_marks = Restrictions.gt("totalMarks", 920);
            Criterion name = Restrictions.ilike("firstName", "Aad%");

            /**
             * To get the records whose totalMarks is 920 or whose name should
             * start with Aad.
             */


            LogicalExpression orExpression = Restrictions.or(total_marks, name);
            criteria3.add(orExpression);

            List<Student> resultsList3 = criteria3.list();

            System.out.println("\n");
            System.out
                    .println("********** USE OF OR EXPRESSION USING CRITERIA API IN HIBERNATE **********");
            System.out
                    .println("################################################################################");
            System.out.println("FIRSTNAME" + "\t LASTNAME" + "\t BIRTHDATE"
                    + "\t TOTAL MARKS" + "\t DIVISION");

            for (Student student : resultsList3) {

                System.out.println("\n");
                System.out.print(student.getFirstName());
                System.out.print("\t\t" + student.getLastName());
                System.out.print("\t\t" + student.getBirthDate());
                System.out.print("\t\t" + student.getTotalMarks());
                System.out.print("\t" + student.getDivision());
            }

            System.out.println("\n\n");
            Criteria criteria4 = session.createCriteria(Student.class);

            /**
             * To get the records whose totalMarks is 920 AND whose name should
             * start with Aad.
             */


            LogicalExpression andExpression = Restrictions.and(total_marks,
                    name);
            criteria4.add(andExpression);

            List<Student> resultsList4 = criteria4.list();

            System.out.println("\n");
            System.out
                    .println("********** USE OF AND EXPRESSION USING CRITERIA API IN HIBERNATE **********");
            System.out
                    .println("################################################################################");
            System.out.println("FIRSTNAME" + "\t LASTNAME" + "\t BIRTHDATE"
                    + "\t TOTAL MARKS" + "\t DIVISION");

            for (Student student : resultsList4) {

                System.out.println("\n");
                System.out.print(student.getFirstName());
                System.out.print("\t\t" + student.getLastName());
                System.out.print("\t\t" + student.getBirthDate());
                System.out.print("\t\t" + student.getTotalMarks());
                System.out.print("\t" + student.getDivision());
            }

            /** Pagination using Criteria API in Hibernate */
            System.out.println("\n\n");
            Criteria criteria5 = session.createCriteria(Student.class);
            criteria5.setFirstResult(1);
            criteria5.setMaxResults(3);
            List<Student> resultsList5 = criteria5.list();
            System.out.println("\n");
            System.out
                    .println("********** PAGINATION USING CRITERIA API IN HIBERNATE **********");
            System.out
                    .println("################################################################################");
            System.out.println("FIRSTNAME" + "\t LASTNAME" + "\t BIRTHDATE"
                    + "\t TOTAL MARKS" + "\t DIVISION");

            for (Student student : resultsList5) {

                System.out.println("\n");
                System.out.print(student.getFirstName());
                System.out.print("\t\t" + student.getLastName());
                System.out.print("\t\t" + student.getBirthDate());
                System.out.print("\t\t" + student.getTotalMarks());
                System.out.print("\t" + student.getDivision());
            }

            /** Sorting the Results Using Criteria API IN Hibernate */
            System.out.println("\n\n");
            Criteria criteria6 = session.createCriteria(Student.class);
            criteria6.add(Restrictions.gt("totalMarks", 900));

            // To sort records in descening order
            criteria6.addOrder(Order.desc("totalMarks"));

            /** To sort records in ascending order
             criteria6.addOrder(Order.asc("totalMarks")); */

            List<Student> resultsList6 = criteria6.list();
            System.out.println("\n");
            System.out
                    .println("********** SORTING THE RESULTS USING CRITERIA API IN HIBERNATE **********");
            System.out
                    .println("################################################################################");
            System.out.println("FIRSTNAME" + "\t LASTNAME" + "\t BIRTHDATE"
                    + "\t TOTAL MARKS" + "\t DIVISION");

            for (Student student : resultsList6) {

                System.out.println("\n");
                System.out.print(student.getFirstName());
                System.out.print("\t\t" + student.getLastName());
                System.out.print("\t\t" + student.getBirthDate());
                System.out.print("\t\t" + student.getTotalMarks());
                System.out.print("\t" + student.getDivision());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();

        }
    }
}

Table Structure and Insert queries are available below:-

/*Table structure for table student */

DROP TABLE IF EXISTS student;

CREATE TABLE student (
  STUDENT_ID decimal(20,0) DEFAULT NULL,
  FIRSTNAME varchar(50) NOT NULL,
  LASTNAME varchar(50) NOT NULL,
  BIRTHDATE date DEFAULT NULL,
  TOTAL_MARKS decimal(20,0) DEFAULT NULL,
  DIVISION varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*Data for the table student */

insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('3','Shivam','Kumar','1989-07-11','670','SECOND');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('2','Gaurav','Kumar','1980-11-19','880','FIRST');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('1','Kumar','Gaurav','1978-05-12','920','FIRST');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('4','Hemant','Raja','1981-02-11','900','FIRST');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('11','Rimi','Kumari','1985-01-31','657','SECOND');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('15','Ram','Reddy','1977-04-22','750','SECOND');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('20','Hansika','Chin','1990-05-13','590','THIRD');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('22','Maduri','Sen','1991-03-18','578','THIRD');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('25','Mili','Kumari','1995-07-19','566','THIRD');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('30','Aaditya','Kumar','1999-08-20','995','FIRST');
insert into student (STUDENT_ID,FIRSTNAME,LASTNAME,BIRTHDATE,TOTAL_MARKS,DIVISION) values ('40','Amit','Sinha','2000-01-14','940','FIRST');

Note:- While running the client program in the database we have below records in the table:-



Required Library files which I am using for the successful execution for this project are as below:-

antlr-2.7.6.jar
asm-2.2.2.jar
asm-commons-2.2.2.jar
cglib-nodep-2.1_3.jar
commons-collections.jar
commons-logging.jar
dom4j-1.6.1.jar
ehcache-1.1.jar
hibernate3.jar
jta.jar
log4j-1.2.14.jar
mysql-connector-java-5.0.4-bin.jar

Result of CriteriaUsingHibernate.java

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select this_.STUDENT_ID as STUDENT1_0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.BIRTHDATE as BIRTHDATE0_0_, this_.TOTAL_MARKS as TOTAL5_0_0_, this_.DIVISION as DIVISION0_0_ from Student this_ where this_.DIVISION=? and this_.TOTAL_MARKS between ? and ?
********** USE OF EQUAL AND BETWEEN EXPRESSION USING CRITERIA API IN HIBERNATE **********
################################################################################
FIRSTNAME     LASTNAME     BIRTHDATE     TOTAL MARKS     DIVISION


Kumar                   Gaurav              1978-05-12             920                FIRST

Hemant                   Raja                1981-02-11             900                 FIRST

Aaditya                   Kumar             1999-08-20             995                FIRST

Amit                       Sinha                2000-01-14             940               FIRST


Hibernate: select this_.STUDENT_ID as STUDENT1_0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.BIRTHDATE as BIRTHDATE0_0_, this_.TOTAL_MARKS as TOTAL5_0_0_, this_.DIVISION as DIVISION0_0_ from Student this_ where this_.TOTAL_MARKS>? and this_.TOTAL_MARKS<? and this_.FIRSTNAME like ?


********** USE OF GREATER THAN, LESS THAN AND LIKE EXPRESSION USING CRITERIA API IN HIBERNATE **********
##################################################################################
FIRSTNAME     LASTNAME     BIRTHDATE     TOTAL MARKS     DIVISION


Hemant                   Raja               1981-02-11               900                FIRST


Hibernate: select this_.STUDENT_ID as STUDENT1_0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.BIRTHDATE as BIRTHDATE0_0_, this_.TOTAL_MARKS as TOTAL5_0_0_, this_.DIVISION as DIVISION0_0_ from Student this_ where (this_.TOTAL_MARKS>? or lower(this_.FIRSTNAME) like ?)


********** USE OF OR EXPRESSION USING CRITERIA API IN HIBERNATE **********
################################################################################
FIRSTNAME     LASTNAME     BIRTHDATE     TOTAL MARKS     DIVISION


Aaditya                  Kumar              1999-08-20           995                  FIRST

Amit                      Sinha                 2000-01-14          940                  FIRST


Hibernate: select this_.STUDENT_ID as STUDENT1_0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.BIRTHDATE as BIRTHDATE0_0_, this_.TOTAL_MARKS as TOTAL5_0_0_, this_.DIVISION as DIVISION0_0_ from Student this_ where (this_.TOTAL_MARKS>? and lower(this_.FIRSTNAME) like ?)


********** USE OF AND EXPRESSION USING CRITERIA API IN HIBERNATE **********
################################################################################
FIRSTNAME     LASTNAME     BIRTHDATE     TOTAL MARKS     DIVISION


Aaditya                   Kumar              1999-08-20        995                    FIRST


Hibernate: select this_.STUDENT_ID as STUDENT1_0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.BIRTHDATE as BIRTHDATE0_0_, this_.TOTAL_MARKS as TOTAL5_0_0_, this_.DIVISION as DIVISION0_0_ from Student this_ limit ?, ?


********** PAGINATION USING CRITERIA API IN HIBERNATE **********
################################################################################
FIRSTNAME     LASTNAME     BIRTHDATE     TOTAL MARKS     DIVISION


Gaurav                   Kumar             1980-11-19             880                  FIRST

Shivam                   Kumar             1989-07-11             670                 SECOND

Hemant                  Raja                  1981-02-11            900                 FIRST


Hibernate: select this_.STUDENT_ID as STUDENT1_0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.BIRTHDATE as BIRTHDATE0_0_, this_.TOTAL_MARKS as TOTAL5_0_0_, this_.DIVISION as DIVISION0_0_ from Student this_ where this_.TOTAL_MARKS>? order by this_.TOTAL_MARKS desc


********** SORTING THE RESULTS USING CRITERIA API IN HIBERNATE **********
################################################################################
FIRSTNAME     LASTNAME     BIRTHDATE     TOTAL MARKS     DIVISION


Aaditya                Kumar                1999-08-20           995                  FIRST

Amit                    Sinha                   2000-01-14          940                  FIRST

Kumar                Gaurav                 1978-05-12          920                  FIRST

No comments:

Post a Comment