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) ); 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 Native SQL queries:
import java.util.*;
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.SQLQuery; import org.hibernate.Criteria; import org.hibernate.Hibernate; 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 employees and their salary using Scalar Query */ ME.listEmployeesScalar(); /* List down complete employees information using Entity Query */ ME.listEmployeesEntity(); } /* 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 using Scalar Query */ publicvoid listEmployeesScalar(){ Session session =factory.openSession(); Transactiontx=null; try{ tx= session.beginTransaction(); String sql ="SELECT first_name, salary FROM EMPLOYEE"; SQLQuery query =session.createSQLQuery(sql); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); List data =query.list(); for(Objectobject: data) { Map row =(Map)object; System.out.print("First Name: "+ row.get("first_name")); System.out.println(", Salary: "+ row.get("salary")); } tx.commit(); }catch(HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); }finally{ session.close(); } } /* Method to READ all the employees using Entity Query */ publicvoid listEmployeesEntity(){ Session session =factory.openSession(); Transactiontx=null; try{ tx= session.beginTransaction(); String sql ="SELECT * FROM EMPLOYEE"; SQLQuery query =session.createSQLQuery(sql); query.addEntity(Employee.class); List employees =query.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(); } } } |