Searching...
Friday, 16 August 2013

Hibernate Criteria Query Simple Example

14:36

Hibernate Criteria API offers to create dynamic queries without using HQL. Here is one simple example to retrieve Student object using Hibernate Criteria.

Software Used

Java 1.7

Hibernate 3

MySql 5

Eclipse Juno

1. Create a Java project

Create a Java project and update Hibernate jars and Mysql driver jar in to build path. (Download Hibernate , MySql Driver)

image

2. Create a Student Entity

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "student", catalog = "hibernateschema")
public class Student  {
    @Id
    @Column(name = "name", unique = true, nullable = false, length = 100)
    private String name;
 
    @Column(name = "standard", unique = true, nullable = false, length = 200)
    private String standard;
   
 
    public String getStandard() {
        return standard;
    }
 
    public void setStandard(String standard) {
        this.standard = standard;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String string) {
        name = string;
    }
 
    public String toString() {
        return name;
    }
}

3. Create Hibernate config file (hibernate.cfg.xml)

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="studentFactory">
            <property name="connection.driver_class">
                 com.mysql.jdbc.Driver
            </property>
        <property name="connection.url">
             jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
             root
        </property>
        <property name="connection.password">
            root
        </property>
            <property name="connection.pool_size">5</property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
             <property name="hbm2ddl.auto">update</property>
             <mapping class="com.pretech.Student"></mapping>
    </session-factory>
</hibernate-configuration>

4.Create a Main program

In this program first we are inserting a student record and retrieving using Hibernate Criteria

package com.pretech;
 
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
 
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
 
public class CriteriaQueryExample {
    private static SessionFactory sessionFactory;
    public static void main(String[] args) {
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
       
       
        //Inserting Student Records
        Transaction tx = session.beginTransaction();
        Student student = new Student();
        student.setName("Raj");
        student.setStandard("10th Standard");
        session.save(student);
        tx.commit();
        System.out.println("Record save successfully");
       
        //Fetching Student object
        Criteria crit = session.createCriteria(Student.class);
        Criterion cn = Restrictions.eq("name","Raj");
        crit.add(cn);
        List l=crit.list();
        Iterator it=l.iterator();
         while(it.hasNext())
        {
             Student stud=(Student)it.next();
            System.out.println(stud.getName());
            System.out.println(stud.getStandard());
            System.out.println("-----------------");
        }
        session.close();
        sessionFactory.close();
    }
 
}

5.Output

Run the main program and see below output

Hibernate: insert into hibernateschema.student (standard, name) values (?, ?)
Record save successfully
Hibernate: select this_.name as name0_0_, this_.standard as standard0_0_ from hibernateschema.student this_ where this_.name=?
Raj
10th Standard
-----------------

0 comments: