Criteria API:
                         Criteria API is used to retrieve the records from the data base server the advantage of this API is we are going to represent the queries in the form of objects.
We can not use Criteria API to insert the record, update the record and delete the record.
The following is an example of using Criteria API to retrieve the records of product table.
Ex:
                    //standard hibernate code
                 
                  

                     //standard hibernate code
                     Session hsession = sf.open Session();
                     Criterial c = hsession.Create Criteria(Product.class);
                     Arraylist list = (Arraylist)c.list();
                     Iterator i = list.iterator();
                     while(i.hasNext()){
                     Product p = (Product);
                     next();
                     System.out.println(p.getPid());
                     System.out.println(p.getName());
                     System.out.println(p.getPrice());
                     }




To work with Criteria API we must follow the following two steps:

1.    Represent the Query in the form of Criteria object.

2.    Send the Criteria to data base server by using a method list();

Hibernate guys has given predefined classes to add the restrictions. They are available as part of org.hibernate.criteria package some of the important classes in that are restrictions,order, property etc.

The following is code to add restrictions to criteria.



                     Criteria c = hsession.create Criteria(Product.class);
                     c.add(Restrictions.ge(“price”,2000d);
                     c.add(Restrictions.le(“price”,4000d);

The Restrictions class contains couple of static factory methods. The internal code of these methods add() the where conditions to the Query as a developer we are responsible to use these methods based on the requirements.

To sort the records based on Criteria API they have provided predefined classes like order. This contains the methods like asc, desc.
Ex:
                   

                Criteria c = hsession.Create Criteria(product.class);
                     c.addOrder(order.desc(“price”));



To retrieve the specific columns from the data base table we use projections class.

Ex:
                    

Criteria c = hsession.Create Criteria(product.class);
                     c.setProjection(Projections.property(“name”));



When we run the above java program the Array list object contains the columns corresponding data type.

adding multiple projections:

                    

Criteria c = hsession.Create Criteria(Product.class);
                     ProjectionList pl = projections.ProjectionList();
                     Pl.add(Projections.property(“name”));
                     Pl.add(Projections.property(“pid”));
                     c.setProjection(pl);


Note:
            Criteria API is not best sui table for the real time projects and to develop complicate Queries for example using the functions like di code, nul1, nul2 etc...

Application for All Projection Operations: 


Employee.java


package a.b;
// Generated Oct 12, 2013 11:57:47 AM by Hibernate Tools 3.2.1.GA

/**
 * Employee generated by hbm2java
 */
public class Employee  implements java.io.Serializable {


     private int empId;
     private String empName;
     private Double empSalary;
     private String empAddress;

    public Employee() {
    }

    
    public Employee(int empId) {
        this.empId = empId;
    }
    public Employee(String empName, Double empSalary, String empAddress) {
    
       this.empName = empName;
       this.empSalary = empSalary;
       this.empAddress = empAddress;
    }
  
    public int getEmpId() {
        return this.empId;
    }
   
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return this.empName;
    }
   
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public Double getEmpSalary() {
        return this.empSalary;
    }
   
    public void setEmpSalary(Double empSalary) {
        this.empSalary = empSalary;
    }
    public String getEmpAddress() {
        return this.empAddress;
    }
   
    public void setEmpAddress(String empAddress) {
        this.empAddress = empAddress;
    }

}


EmpDAO.java

package a.b;

import a.b.Employee;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Personal
 */
public class EmpDAO {
    private static SessionFactory  factory;
    private static Session session;
    private static Transaction transaction;
    static
    {
     factory=new Configuration().configure().buildSessionFactory();
    }
    public static void addEmployeeDetails(Employee employee)
    {
        try {
            session = factory.openSession();
            transaction = session.beginTransaction();
            session.save(employee);
            transaction.commit();
        } catch (HibernateException hibernateException) {
            hibernateException.printStackTrace();
            transaction.rollback();
            throw hibernateException;
            
        }
        finally{
           
            session.close();
        }
       
    }
    public static List<Employee> getEmployeeDetails()
    {
        session=factory.openSession();
        transaction=session.beginTransaction();
       Criteria criteria=session.createCriteria(Employee.class);
       List<Employee> employees=(List<Employee>)criteria.list();
      transaction.commit();
       session.close();
       return employees;
       
    }

    public static List<Employee> getEmployeeDetails(double range){
         session=factory.openSession();
        transaction=session.beginTransaction();
       Criteria criteria=session.createCriteria(Employee.class);
       criteria.add(Restrictions.gt("empSalary", range));
       List<Employee> employees=(List<Employee>)criteria.list();
      
      transaction.commit();
       session.close();
       return employees;
      
    }
    public static List<Employee> getEmployeeDetail() {
         session=factory.openSession();
        transaction=session.beginTransaction();
       Criteria criteria=session.createCriteria(Employee.class);
      
       List<Employee> employees=(List<Employee>)criteria.list();
      transaction.commit();
       session.close();
       return employees;
      
    }

    public static List<Employee> getEmployeeEquall(double range) {
       
       session=factory.openSession();
       transaction=session.beginTransaction();
       Criteria criteria=session.createCriteria(Employee.class);
       criteria.add(Restrictions.eq("empSalary", range));
       List<Employee> employees=(List<Employee>)criteria.list();
       transaction.commit();
       session.close();
       return employees;
    }
   public static void updateEmployee(int empId,double updateSalary)
    {

       session=factory.openSession();
       transaction=session.beginTransaction();
       Criteria criteria=session.createCriteria(Employee.class);
      
       List<Employee> employees=(List<Employee>)criteria.list();
       transaction.commit();
       session.close();
      
    }

public staticList<Employee> getEmployeeDetailsUsingLikeEmpName
(String ename) {

      session=factory.openSession();
      transaction=session.beginTransaction();
      Criteria criteria=session.createCriteria(Employee.class);
      criteria.add(Restrictions.like("empName", ename+"%"));
       List<Employee> employees=(List<Employee>)criteria.list();
       transaction.commit();
       session.close();
       return employees;
    }

public static List<Employee> getEmployeeSalariesSalaryBetween
(double start, double end) {

       session=factory.openSession();
      transaction=session.beginTransaction();
      Criteria criteria=session.createCriteria(Employee.class);
      criteria.add(Restrictions.between("empSalary", start,end));
       List<Employee> employees=(List<Employee>)criteria.list();
       transaction.commit();
       session.close();
       return employees;
    }

public static List<Employee> getEmployeeSalariesSalaryBetweenWithSorting
(double start, double end) {

        session=factory.openSession();
      transaction=session.beginTransaction();
      Criteria criteria=session.createCriteria(Employee.class);
      criteria.add(Restrictions.between("empSalary", start,end));
      criteria.addOrder(Order.asc("empSalary"));
       List<Employee> employees=(List<Employee>)criteria.list();
       transaction.commit();
       session.close();
       return employees;
    }

    public static void projectionExamples()
    {
        session=factory.openSession();
        transaction=session.beginTransaction();
        Criteria criteria=session.createCriteria(Employee.class);
        criteria.setProjection(Projections.rowCount());

       System.out.println("\t Row Count :"+criteria.list().get(0));
        criteria.setProjection(Projections.avg("empSalary"));

  System.out.println("\t Employees Salarys Average is :"+criteria.list().get(0));

        criteria.setProjection(Projections.sum("empSalary"));

    System.out.println("\t Employees Salarys Total Sum  is :"+criteria.list().get(0));

        criteria.setProjection(Projections.min("empSalary"));

 System.out.println("\tEmployees Min Salarys is :"+criteria.list().get(0));

        criteria.setProjection(Projections.max("empSalary"));

System.out.println("\tEmployees Max Salarys is :"+criteria.list().get(0));
        criteria.setProjection(Projections.groupProperty("empAddress"));

        List address=criteria.list();
        for(Object add:address)
        {
        System.out.println(" Address is: :"+add);    
        }
       
    }
    public static void projectionsUsingProjectList()
    {
        session=factory.openSession();
        transaction=session.beginTransaction();
        Criteria criteria=session.createCriteria(Employee.class);
        ProjectionList projectionList=Projections.projectionList();
        projectionList.add(Projections.rowCount());
        projectionList.add(Projections.avg("empSalary"));
        projectionList.add(Projections.max("empSalary"));
        projectionList.add(Projections.min("empSalary"));
        projectionList.add(Projections.sum("empSalary"));
        projectionList.add(Projections.groupProperty("empAddress"));
        criteria.setProjection(projectionList);
        List<Employee> list=criteria.list();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Object ob[] = (Object[])it.next();
            System.out.println(ob[0]+"--------"+ob[1]+""
                    + "--------"+ob[2]+"--------"+ob[3]+""
                    + ""+"--------"+ob[4]+""+"--------"+ob[5]+"");
           
        }
    }
    public static void requiredFeeldsOnly()
    {
         session=factory.openSession();
        transaction=session.beginTransaction();
        Criteria criteria=session.createCriteria(Employee.class);
        ProjectionList projectionList=Projections.projectionList();
        projectionList.add(Projections.property("empName"));
        projectionList.add(Projections.alias(Projections.property("empSalary"), "employee_Salary"));
        criteria.setProjection(projectionList);
       
        List list=criteria.list();
       for(Object obj1:list)
       {
           Object obj2[]=(Object[])obj1;
           for(Object obj3:obj2)
           {
                    System.out.println(" Employee Details :"+obj3);         
           }
           System.out.println("\n **");
                       
       }
              
    }
}


HibernateCriteria.java

package a.b;

import a.b.EmpDAO;
import a.b.Employee;

import java.util.List;

/**
 *
 * @author Personal
 */

public class HibernateCriteria {
  public static void main(String[] args) {

        HibernateCriteria controller=new HibernateCriteria();
        //controller.preSettings(controller);

        controller.getEmployeeDetails();
        controller.getEmployeeSalariesGatherThan(20000);
        controller.getEmployeeSalariesEquall(20000);
        controller.getEmployeeDetailsUsingLikeEmpName("siva");
         controller.getEmployeeSalariesSalaryBetween(1,10000);
       controller.getEmployeeSalariesSalaryBetweenWithSorting(10000,30000);
        System.out.println("\n\n All Projections Examples \n");
        controller.projectExamples();
        System.out.println("\n\n Single Seeting Projections Examples \n");
        controller.projectionsUsingProjectList();
       System.out.println("\n\n Required Fields Only ");
       controller. requiredFeeldsOnly();
    }
    

    private void addEmployeeDetails(Employee employee)
    {
        EmpDAO.addEmployeeDetails(employee);
   

    private void getEmployeeDetails()
    {
        List<Employee> employees=EmpDAO.getEmployeeDetails();
        System.out.println("\n\n No Criteria Restriction\n ");
        displayData(employees);
               
    }

    private void getEmployeeSalariesGatherThan(double range)
    {
        List<Employee> employees=EmpDAO.getEmployeeDetails(range);
        System.out.println("\n\n Criteria Restriction Grather Than\n");               
        displayData(employees);
               
    }

  private void getEmployeeSalariesSalaryBetween
(double start,double end)
    {
 List<Employee> employees=
EmpDAO.getEmployeeSalariesSalaryBetween(start,end);

        System.out.println("\n\n Criteria Restriction Salaries In Between\n");  
             
        displayData(employees);
               
    }


    private void getEmployeeSalariesSalaryBetweenWithSorting(double start,double end)
    {
        List<Employee> employees=EmpDAO.getEmployeeSalariesSalaryBetweenWithSorting(start,end);
        System.out.println("\n\n Criteria Restriction Salaries In Between With Sorting\n");               
        displayData(employees);
               
    }

  
    private void getEmployeeDetailsUsingLikeEmpName(String ename)
    {
        List<Employee> employees=EmpDAO.getEmployeeDetailsUsingLikeEmpName(ename);
        System.out.println("\n\n Criteria Restriction Like  \n");               
        displayData(employees);
    }

    private void getEmployeeSalariesEquall(double range)
    {
        List<Employee> employees=EmpDAO.getEmployeeEquall(range);
        System.out.println("\n\n Criteria Restriction Equalls \n");               
        displayData(employees);
               
    }

    private void displayData(List<Employee> employees)
    {
        for(Employee employee:employees)

        System.out.println(" Employee Id :"+employee.getEmpId()+""
                    + "\t Employee Name :"+employee.getEmpName()+""
                    + "\t Employee Salary :"+employee.getEmpSalary()+""
                    + "\t Employee Address :"+employee.getEmpAddress());
                   
           
    }
   
 

    private void projectExamples() {
       EmpDAO.projectionExamples();
    }

    private void projectionsUsingProjectList(){
       EmpDAO.projectionsUsingProjectList();
    }


    private void requiredFeeldsOnly() {
        EmpDAO.requiredFeeldsOnly();
    }
   
   
}


Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 12, 2013 11:57:47 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="a.b.Employee" table="employee" catalog="ashok">
        <id name="empId" type="int">
            <column name="empId" />
            <generator class="assigned" />
        </id>
        <property name="empName" type="string">
            <column name="empName" />
        </property>
        <property name="empSalary" type="java.lang.Double">
            <column name="empSalary" precision="22" scale="0" />
        </property>
        <property name="empAddress" type="string">
            <column name="empAddress" />
        </property>
    </class>
</hibernate-mapping>

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.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ashok</property>
    <property name="hibernate.connection.username">root</property>
    <mapping resource="a/b/Employee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


hibernate.reveng.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="ashok"/>
  <table-filter match-name="employee"/>
</hibernate-reverse-engineering>



Out put:( Screen Shot For Application)



Table creation for employee


mysql> CREATE TABLE `employee` (
    -> `empId` INT(11) NOT NULL,
    -> `empName` VARCHAR(255) NULL DEFAULT NULL,
    -> `empSalary` DOUBLE NULL DEFAULT NULL,
    -> `empAddress` VARCHAR(255) NULL DEFAULT NULL,
    -> PRIMARY KEY (`empId`)
    -> );
Query OK, 0 rows affected (0.30 sec)

Fetching Records for Employee

mysql> select * from employee;
+-------+---------+-----------+------------+
| empId | empName | empSalary | empAddress |
+-------+---------+-----------+------------+
|     1 | avanthi |     10000 | gdvl       |
|     2 | ashok   |     20000 | gdv        |
|     3 | teja    |     30000 | gdv        |
|     4 | siva    |     40000 | gdv        |
|     5 | chamu   |     40000 | gdv        |
|     6 | chamu   |     40000 | gdv        |
|     8 | chamu   |     40000 | gdv        |
|     9 | chamu   |     40000 | gdv        |
|    10 | chamu   |     40000 | gdv        |
|    11 | chamu   |     40000 | gdv        |
|    12 | chamu   |     40000 | gdv        |
+-------+---------+-----------+------------+
11 rows in set (0.00 sec)


After Running the application:

 No Criteria Restriction
 Employee Id :1   Employee Name :avanthi            Employee Salary :10000.0            Employee Address :gdvl
 Employee Id :2  Employee Name :ashok               Employee Salary :20000.0             Employee Address :gdv
 Employee Id :3  Employee Name :teja                    Employee Salary :30000.0            Employee Address :gdv
 Employee Id :4  Employee Name :siva                   Employee Salary :40000.0             Employee Address :gdv
 Employee Id :5  Employee Name :chamu               Employee Salary :40000.0            Employee Address :gdv
 Employee Id :6  Employee Name :chamu               Employee Salary :40000.0            Employee Address :gdv
 Employee Id :8  Employee Name :chamu               Employee Salary :40000.0            Employee Address :gdv
 Employee Id :9  Employee Name :chamu               Employee Salary :40000.0            Employee Address :gdv
 Employee Id :10  Employee Name :chamu             Employee Salary :40000.0            Employee Address :gdv
 Employee Id :11 Employee Name :chamu              Employee Salary :40000.0            Employee Address :gdv
 Employee Id :12  Employee Name :chamu             Employee Salary :40000.0            Employee Address :gdv


 Criteria Restriction Grather Than

 Employee Id :3  Employee Name :teja      Employee Salary :30000.0           Employee Address :gdv
 Employee Id :4  Employee Name :siva      Employee Salary :40000.0           Employee Address :gdv
 Employee Id :5  Employee Name :chamu  Employee Salary :40000.0           Employee Address :gdv
 Employee Id :6  Employee Name :chamu  Employee Salary :40000.0           Employee Address :gdv
 Employee Id :8  Employee Name :chamu   Employee Salary :40000.0          Employee Address :gdv
 Employee Id :9  Employee Name :chamu   Employee Salary :40000.0          Employee Address :gdv
 Employee Id :10 Employee Name :chamu   Employee Salary :40000.0         Employee Address :gdv
 Employee Id :11 Employee Name :chamu   Employee Salary :40000.0         Employee Address :gdv
 Employee Id :12  Employee Name :chamu  Employee Salary :40000.0         Employee Address :gdv
 Criteria Restriction Equalls
 Employee Id :2  Employee Name :ashok Employee Salary :20000.0            Employee Address :gdv
 Criteria Restriction Like 
 Employee Id :4  Employee Name :siva     Employee Salary :40000.0            Employee Address :gdv
 Criteria Restriction Salaries In Between
 Employee Id :1  Employee Name :avanthi             Employee Salary :10000.0            Employee Address :gdvl
 Criteria Restriction Salaries In Between With Sorting
 Employee Id :1  Employee Name :avanthi    Employee Salary :10000.0       Employee Address :gdvl
 Employee Id :2  Employee Name :ashok Employee Salary :20000.0            Employee Address :gdv
 Employee Id :3  Employee Name :teja     Employee Salary :30000.0            Employee Address :gdv
 All Projections Examples
 Row Count :11
 Employees Salarys Average is :34545.454545455
 Employees Salarys Total Sum  is :380000.0
 Employees Min Salarys is :10000.0
Employees Max Salarys is :40000.0
 Address is: :gdv
 Address is: :gdvl
 Single Seeting Projections Examples
10--------37000.0--------40000.0--------20000.0--------370000.0--------gdv
1--------10000.0--------10000.0--------10000.0--------10000.0--------gdvl
 Required Fields Only
 Employee Details :avanthi
 Employee Details :10000.0
 **
 Employee Details :ashok
 Employee Details :20000.0
 **
 Employee Details :teja
 Employee Details :30000.0
 **
 Employee Details :siva
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
 Employee Details :chamu
 Employee Details :40000.0
 **
BUILD SUCCESSFUL (total time: 3 seconds)

 

Download For Application Click Here




0 comments:

Post a Comment