Thursday, January 10, 2013

Hibernate : Pagination of the Data using HQL


Most common way of fetching the database record using HQL is
Query query = session.createQuery(from Employee)

but if your query result in some large data then its going to consume a lot of Memory
and can possibly going to slow your program as it would require to process lots of data
but hibernate provide a convenient approach using HQL pagination through which you can limit the no of records return by the database.

Lets walk through the fallowing code which will give you overview to use HQL as well as the Hibernate pagination.

lets create your Model class as fallows and annotate with it with the javax.persistence

package com.rajkrrsinghblogspot.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="EMP_TABLE")
public class Employee {

@Id
private int empid;
private String empName;

public Employee(){

}

public Employee(int empid,String empName){
this.empid = empid;
this.empName = empName;
}


public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}

public String toString(){
return "::EMPID::"+getEmpid()+"::EMPNAME::"+getEmpName()+"::";
}


}

Create Hibernate.cfg.xml as fallows and keep it in the classpath
<?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>

<!-- Database connection settings -->
<property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="connection.url">jdbc:derby://localhost:1527/MyHibDB;create=true</property>
<property name="connection.username">rajkumar</property>
<property name="connection.password">rajkumar</property>


<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>

<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>

<mapping class="com.rajkrrsinghblogspot.model.Employee"/>

</session-factory>

</hibernate-configuration>

Now Create your main class to persist the database into the database and also retrive the result form database using HQL as fallows
package com.rajkrrsingh;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.rajkrrsinghblogspot.model.Employee;


public class App
{
public static void main( String[] args )
{
System.out.println("Testing my hibernate configuration");

Employee emp = null;
List<Employee> list = new ArrayList<Employee>();

for(int i=0;i<10;i++){
emp = new Employee(i, "Emp"+i);
list.add(emp);
}

SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
for(Employee e : list){
session.save(e);
}

session.getTransaction().commit();
session.close();

session = sf.openSession();
session.beginTransaction();
Query query = session.createQuery("from Employee");
query.setFirstResult(1);
query.setMaxResults(3);
List<Employee> empList = query.list();

System.out.println("\n");
System.out.println("Printing 3 results from HQL using Pagination");
System.out.println("\n");
for(Employee em : empList){
System.out.println(em);
}

session.getTransaction().commit();
session.close();
}
}


After running this example you will find the fallowing output on the console





Saturday, January 5, 2013

Hibernate : CRUD Operations on the objects

Here I have demonstrated the basic CRUD operation using Hibernate API

To add records to the database, all you need to do it create an instance of your Model Class, create an instance of the Hibernate SessionFactory, grab an actual Hibernate Session from that factory start a transaction, pass your POJO instance to the save method of the Session, and then commit the transaction.

we can use the get method of the Hibernate Session to pull that instance out of the database, simply by passing in the class type and the primary key as arguments:

The get method of the Hibernate Session will return one entity. If you need to return multiple entities, you create a Hibernate query. you can use a Hibernate query to grab every record in the database as a list.

To delete a record, simply obtain the record from Hibernate using the get method and then pass the obtained object to the delete method of the Hibernate Session, all within an active transaction.

Here is the complete code to obtain all this in same place.

Create your project structure as shown in figure and add the hibernate related configuration to the project if you are not familier with hibernate configuration then fallow this link : Configuration and setting of Hibernate




















Configure hibernate.cfg.xml as fallows
<?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>

<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/deptt</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>


<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>


<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<mapping class="com.rajkrrsinghblogspot.model.Employee"/>

</session-factory>

</hibernate-configuration>



Create your Model class and annotate it with javax.persistance annotation
package com.rajkrrsinghblogspot.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="EMPLOYEE")
public class Employee {

@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="EMPID")
private int empId;

@Column(name="EMP_NAME")
private String empName;

@Column(name="DESIGNATION")
private String designation;

public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}



}


Create HibernateUtil class to expose the SessionFactory when required instead of recreate every time.
package com.rajkrrsinghblogspot.sessionfactory;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtilImpl  {

private static SessionFactory sessionFactory;

public static  SessionFactory getSessionFacotry(){
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch(HibernateException he){
he.printStackTrace();
}
return sessionFactory;
}

}


Now Create your Main class to test out all the operation.
package com.rajkrrsinghblogspot.main;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.rajkrrsinghblogspot.model.Employee;
import com.rajkrrsinghblogspot.sessionfactory.HibernateUtilImpl;

public class MainClass {

public static void main(String[] args) {
//createEmployee();
//readEmployee();
//updateEmployee();
deleteEmployee();
}


private static void createEmployee() {
Employee emp = new Employee();
emp.setEmpName("Amit Singh");
emp.setDesignation("Managar");

Employee empp = new Employee();
empp.setEmpName("Vijay Singh");
empp.setDesignation("TL");

SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();
session.save(emp);
session.save(empp);
session.getTransaction().commit();
session.close();

}


private static void readEmployee() {
Employee emp1 = new Employee();

SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();

// provided primary key to get the perticular record
emp1 = (Employee) session.get(Employee.class, 1);
System.out.println("The name of employee is "+emp1.getEmpName()+" And the designation of Emp is "
+emp1.getDesignation());
session.getTransaction().commit();
session.close();

// to selector list all the record in the table using HQL
session = sf.openSession();
session.beginTransaction();
Query query = session.createQuery("from Employee");
List<Employee> list = query.list();
System.out.println("\n");
System.out.println("::::::::::Printing Emp Details:::::::::::");
System.out.println("\n");
for(Employee emp : list){
System.out.println("Emp id is "+emp.getEmpId()+" Emp Name is "+emp.getEmpName()
+" and the designation is "+emp.getDesignation());
}
session.getTransaction().commit();
session.close();

}

private static void updateEmployee() {
Employee emp1 = new Employee();

SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();

// provided primary key to get the perticular record
emp1 = (Employee) session.get(Employee.class, 1);
emp1.setDesignation("SSE");
System.out.println("Designation updated successfully");
session.getTransaction().commit();
session.close();

}
private static void deleteEmployee() {
SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();
// getting the object using load method instead of using get method
Employee emp = (Employee) session.load(Employee.class, 1);
session.delete(emp);
System.out.println("Employee Deleted");
session.getTransaction().commit();
session.clear();
}



}
To test the main class uncomment the method in main method one by one to test each operation.

Thanks and Happy Learniing


HIbernate saving images in database

HIbernate : Configuration and Setting up of the project