The largest Interview Solution Library on the web


Hibernate Tutorials/
« Previous | 1 | 2 | 3 | Next »
Consider the following POJO class:

publicclassEmployee{
privateint id;
privateString firstName;
privateString lastName; privateint salary;<

publicEmployee(){}
publicEmployee(String fname,String lname,int salary){
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
publicint getId(){
return id;
}
publicvoid setId(int id ){
this.id = id;
}
publicString getFirstName(){
return firstName;
}
publicvoid setFirstName(String first_name ){
this.firstName = first_name;
}
publicString getLastName(){
return lastName;
}
publicvoid setLastName(String last_name ){
this.lastName = last_name;
}
publicint getSalary(){
return salary;
}
publicvoid setSalary(int salary ){
this.salary = salary;
}
}

Let us create the following EMPLOYEE table to store Employee objects:

create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20)default NULL,
last_name VARCHAR(20)default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

Following will be mapping file.

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

<hibernate-mapping>
<classname="Employee"table="EMPLOYEE">
<metaattribute="class-description">
This class contains the employee detail.
</meta>
<idname="id"type="int"column="id">
<generatorclass="native"/>
</id>
<propertyname="firstName"column="first_name"type="string"/>
<propertyname="lastName"column="last_name"type="string"/>
<propertyname="salary"column="salary"type="int"/>
</class>
</hibernate-mapping>

Finally, we will create our application class with the main() method to run the application where we will use Criteria queries:

import java.util.List;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;
import org.hibernate.cfg.Configuration;

publicclassManageEmployee{
privatestaticSessionFactory factory;
publicstaticvoid main(String[] args){
try{
factory=newConfiguration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("Failed to create sessionFactory object."+ex);
thrownewExceptionInInitializerError(ex);
}
ManageEmployee ME =newManageEmployee();

/* Add few employee records in database */
Integer empID1 =ME.addEmployee("Zara","Ali",2000);
Integer empID2 =ME.addEmployee("Daisy","Das",5000);
Integer empID3 =ME.addEmployee("John","Paul",5000);
Integer empID4 =ME.addEmployee("Mohd","Yasee",3000);

/* List down all the employees */
ME.listEmployees();

/* Print Total employee's count */
ME.countEmployee();

/* Print Toatl salary */
ME.totalSalary();
}
/* Method to CREATE an employee in the database */
publicInteger addEmployee(String fname,String lname,int salary){
Session session =factory.openSession();
Transactiontx=null;
Integer employeeID =null;
try{
tx= session.beginTransaction();
Employee employee =newEmployee(fname, lname, salary);
employeeID=(Integer) session.save(employee);
tx.commit();
}catch(HibernateException e){
if(tx!=null) tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
return employeeID;
}

/* Method to READ all the employees having salary more than 2000 */
publicvoid listEmployees(){
Session session =factory.openSession();
Transactiontx=null;
try{
tx= session.beginTransaction();
Criteria cr =session.createCriteria(Employee.class);
// Add restriction.
cr.add(Restrictions.gt("salary",2000));
List employees =cr.list();

for(Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee =(Employee)iterator.next();
System.out.print("First Name: "+ employee.getFirstName());
System.out.print(" Last Name: "+ employee.getLastName());
System.out.println(" Salary: "+ employee.getSalary());
}
tx.commit();
}catch(HibernateException e){
if(tx!=null) tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
}
/* Method to print total number of records */
publicvoid countEmployee(){
Session session =factory.openSession();
Transactiontx=null;
try{
tx= session.beginTransaction();
Criteria cr =session.createCriteria(Employee.class);

// To get total row count.
cr.setProjection(Projections.rowCount());
List rowCount =cr.list();

System.out.println("Total Coint: "+ rowCount.get(0));
tx.commit();
}catch(HibernateException e){
if(tx!=null) tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
}
/* Method to print sum of salaries */
publicvoid totalSalary(){
Session session =factory.openSession();
Transactiontx=null;
try{
tx= session.beginTransaction();
Criteria cr =session.createCriteria(Employee.class);

// To get total salary.
cr.setProjection(Projections.sum("salary"));
List totalSalary =cr.list();

System.out.println("Total Salary: "+ totalSalary.get(0));
tx.commit();
}catch(HibernateException e){
if(tx!=null) tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
}
}
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com