hibernate handout

33
Preparing the set-up 1. Execute run.bat file 2. Open DBVisualizer 3. Go to Database menu a. Click on Create Database Connection b. Enter the connection alias – localhost c. Click next d. From Select Database Driver, select HSQLDB server e. It will ask to load driver files f. From lib folder, select hsqldb.jar g. Click next h. Give port: 8887 and username : sa i. Click test connection, You should get “Connection Successfully established” Example:1: Hibernate One Tasks: a. Creating a table b. Inserting records Employee.java package com.hibernate; public class Employee { private int eid; private String ename; private String edepartment; private String edesignation; public String getEdepartment() { return edepartment; } public void setEdepartment(String edepartment) { this.edepartment = edepartment; } public String getEdesignation() { return edesignation; } public void setEdesignation(String edesignation) { this.edesignation = edesignation; } public int getEid() { return eid;

Upload: kamalakar-dandu

Post on 15-May-2015

351 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Hibernate handout

Preparing the set-up1. Execute run.bat file2. Open DBVisualizer3. Go to Database menu

a. Click on Create Database Connectionb. Enter the connection alias – localhostc. Click nextd. From Select Database Driver, select HSQLDB servere. It will ask to load driver filesf. From lib folder, select hsqldb.jarg. Click nexth. Give port: 8887 and username : sai. Click test connection, You should get “Connection Successfully

established”

Example:1: Hibernate OneTasks:

a. Creating a tableb. Inserting records

Employee.javapackage com.hibernate;

public class Employee {private int eid;private String ename;private String edepartment;private String edesignation;public String getEdepartment() {

return edepartment;}public void setEdepartment(String edepartment) {

this.edepartment = edepartment;}public String getEdesignation() {

return edesignation;}public void setEdesignation(String edesignation) {

this.edesignation = edesignation;}public int getEid() {

return eid;}public void setEid(int eid) {

this.eid = eid;}public String getEname() {

return ename;}public void setEname(String ename) {

this.ename = ename;}}

Page 2: Hibernate handout

EmployeeClient.java

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import com.hibernate.Employee;

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

SessionFactory sf=new Configuration().configure().buildSessionFactory();

Session s=null;s=sf.openSession();Employee emp=new Employee();emp.setEid(100);emp.setEname("JP");emp.setEdepartment("LKM");emp.setEdesignation("Software Engineer");s.save(emp);s.flush();

}}

Hibernate.cfg.xml<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property><property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:8887</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> // show_sql for showing the query statement <property name="format_sql">true</property> // format_sql for showing the formatted query statement <property name="dialect">org.hibernate.dialect.HSQLDialect </property> <property name="hibernate.hbm2ddl.auto">create</property>

<mapping resource="employee.hbm.xml"/> </session-factory>

</hibernate-configuration>

Page 3: Hibernate handout

Notes: If you want to create a new table everytime, go for:

<property name="hibernate.hbm2ddl.auto">create</property>

For inserting new records, change the above value to update.If you want to make any change corresponding to eid(primary key column), use s.update(emp) instead of s.save(emp) in EmployeeClient.java. s.save(emp) creates a new record.So if you have created any primary key, error would be there.It’s better to go for s.saveOrUpdate(emp).For deleting a particular record, you can use s.delete(emp).

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">

<hibernate-mapping> <class name="com.hibernate.Employee" table="employeedemo">

<id name="eid" type="int" unsaved-value="0"><generator class="assigned"/>

</id><property name="ename" /><property name="edepartment"/><property name="edesignation"/>

</class></hibernate-mapping>

Example:2:HibernateOneTasksEmployeeRetrieve.javapackage client;

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

import com.hibernate.Employee;

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

SessionFactory sf=new Configuration().configure().buildSessionFactory();

Session s=null;s=sf.openSession();Employee emp=new Employee();emp=(Employee) s.get(Employee.class, new Integer(1));System.out.println("Employee loaded from the database");System.out.println("Name:"+emp.getEname());System.out.println("Departmet:"+emp.getEdepartment());System.out.println("Designation:"+emp.getEdesignation());

}}

Page 4: Hibernate handout

Example:3:OneToOne(User----- UserDetails) User.javapackage com;

public class User {

private String userId = null;

private String userType = null;

private UserDetails userDetails = null;

public User() { }

public String getUserId() { return userId; }

public void setUserId(String userId) { this.userId = userId; }

public String getUserType() { return userType; }

public void setUserType(String userType) { this.userType = userType; }

public UserDetails getUserDetails() { return userDetails; }

public void setUserDetails(UserDetails userDetails) { this.userDetails = userDetails; }

}

UserDetails.javapackage com;

public class UserDetails {

private String userId = null;

public User getUser() { return user; }

public void setUser(User user) { this.user = user; }

Page 5: Hibernate handout

public String getUserId() { return userId; }

public void setUserId(String userId) { this.userId = userId; }

private User user = null;

private String userFirstName = null;

private String userWorkPhone = null;

public UserDetails() { }

public String getUserFirstName() { return userFirstName; }

public void setUserFirstName(String userFirstName) { this.userFirstName = userFirstName; }

public String getUserWorkPhone() { return userWorkPhone; }

public void setUserWorkPhone(String userWorkPhone) { this.userWorkPhone = userWorkPhone; }

}

UserClient.java

package client;

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.*;

public class UserClient {

public static void main(String[] args) {

User user = new User(); user.setUserId("testuser4"); user.setUserType("S3");

UserDetails userDetails = new UserDetails(); userDetails.setUserFirstName("raj"); userDetails.setUserWorkPhone("99");

Page 6: Hibernate handout

user.setUserDetails(userDetails); userDetails.setUser(user);

SessionFactory sf = new Configuration().configure() .buildSessionFactory(); Session session = sf.openSession();

Transaction tx = session.beginTransaction(); session.update(user); tx.commit();

}}Hibernate.cfg.xml<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property><property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:8887</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="dialect">org.hibernate.dialect.HSQLDialect </property> <property name="hibernate.hbm2ddl.auto">update</property>

<mapping resource="User.hbm.xml"/>

</session-factory></hibernate-configuration>

User.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">

<hibernate-mapping > <class name="com.User" table="user"> <id name="userId" column="user_id"> <generator class="assigned"/> </id> <property name="userType"> <column name="user_type_id" /> </property>

Page 7: Hibernate handout

<one-to-one name="userDetails" class="com.UserDetails" cascade="all" /> </class>

<class name="com.UserDetails" table="user_details"> <id name="userId" column="user_id"> <generator class="foreign"> <param name="property">user</param> </generator> </id> <one-to-one name="user" class="com.User" /> <property name="userFirstName"> <column name="user_first_name" /> </property> <property name="userWorkPhone"> <column name="user_work_phone" /> </property> </class></hibernate-mapping>

Example:4: OneToMany(HighScores--- GameScore)

HighScores.javapackage com;

import java.util.*;

public class HighScores { private int id;

private String name;

private Set games;

public HighScores() { System.out.println(""); }

public HighScores(String name) { this.name = name; }

public void setId(int i) { id = i; }

public int getId() { return id; }

public void setName(String n) { name = n; }

Page 8: Hibernate handout

public String getName() { return name; }

public void setGames(Set games) { this.games = games; }

public Set getGames() { return games; }}

GameScore.javapackage com;

public class GameScore { private int id;

private String name;

private int score;

public GameScore() { }

public GameScore(String name, int score) { this.name = name; this.score = score; }

public void setId(int i) { id = i; }

public int getId() { return id; }

public void setName(String s) { name = s; }

public String getName() { return name; }

public void setScore(int i) { score = i; }

public int getScore() { return score; }

public boolean equals(Object obj) {

Page 9: Hibernate handout

if (obj == null) return false; if (!this.getClass().equals(obj.getClass())) return false;

GameScore obj2 = (GameScore) obj;

if ((this.id == obj2.getId()) && (this.name.equals(obj2.getName())) && (this.score == obj2.getScore())) { return true; }

return false; }

public int hashCode() { int tmp = 0; tmp = (id + name + score).hashCode();

return tmp; }}

HighScores.hbm.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com"><class name="HighScores"

table="highscores"> <id name="id" >

<generator class="hilo"/></id>

<set name="games" cascade="all"><key column="parent_id"/><one-to-many class="GameScore"/>

</set><property name="name" type="string"/>

</class>

<class name="GameScore" table="gamescores"> <id name="id" >

<generator class="increment"/></id>

<property name="name"/> <property name="score"/></class>

</hibernate-mapping>

Page 10: Hibernate handout

Example:4: OneToMany(Bi-directional-Group--- Member)

Group.java

package com;

import java.util.Set;

public class Group {private int id;private String name;private double budget;private Set memberSet;

public int getId() {return id;

}public void setId(int id) {

this.id = id;}public Set getMemberSet() {

return memberSet;}public void setMemberSet(Set memberSet) {

this.memberSet = memberSet;}public String getName() {

return name;}public void setName(String name) {

this.name = name;}public double getBudget() {

return budget;}public void setBudget(double budget) {

this.budget = budget;}}

Member.javapackage com;

public class Member {

private int id;private String name;private String phone;private double salary;private Group group;

Page 11: Hibernate handout

public int getId() {return id;

}public void setId(int id) {

this.id = id;}public String getName() {

return name;}public void setName(String name) {

this.name = name;}public String getPhone() {

return phone;}public void setPhone(String phone) {

this.phone = phone;}public double getSalary() {

return salary;}public void setSalary(double salary) {

this.salary = salary;}public Group getGroup() {

return group;}public void setGroup(Group group) {

this.group = group;}}

GroupClient.javapackage client;

import java.util.HashSet;import java.util.Set;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.Group;import com.Member;

public class GroupClient {

public static void main(String[] args) {SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();Group group1 = new Group();group1.setId(1);group1.setName("Group 1");group1.setBudget(1000);

Page 12: Hibernate handout

Group group2 = new Group();group2.setId(2);group2.setName("Group 2");group2.setBudget(2000);

Member member1 = new Member();member1.setId(1);member1.setName("A");member1.setPhone("123");member1.setSalary(100);member1.setGroup(group1);session.save(member1);

Member member2 = new Member();member2.setId(2);member2.setName("B");member2.setPhone("123");member2.setSalary(200);member2.setGroup(group1);session.save(member2);

Member member3 = new Member();member3.setId(3);member3.setName("C");member3.setPhone("123");member3.setSalary(300);member3.setGroup(group2);session.save(member3);

Member member4 = new Member();member4.setId(4);member4.setName("D");member4.setPhone("123");member4.setSalary(400);member4.setGroup(group2);session.save(member4);

Set memberSet1 = new HashSet();memberSet1.add(member1);memberSet1.add(member2);

Set memberSet2 = new HashSet();memberSet2.add(member3);memberSet2.add(member4);

group1.setMemberSet(memberSet1);group2.setMemberSet(memberSet2);

session.save(group1);session.save(group2);

transaction.commit();session.close();

}

}

Page 13: Hibernate handout

Hibernate.cfg.xml<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property><property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:8887</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="dialect">org.hibernate.dialect.HSQLDialect </property> <property name="hibernate.hbm2ddl.auto">create</property>

<mapping resource="member.hbm.xml"/> </session-factory>

</hibernate-configuration>

Member.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">

<hibernate-mapping> <class name="com.beans.Group" table="MEM_GROUP"> <id name="id" type="int" column="group_id"> <generator class="assigned"/> </id> <property name="name"> <column name="NAME" /> </property> <property name="budget"> <column name="BUDGET" /> </property> <set name="memberSet" lazy="true" > <key column="group_id"/> <one-to-many class="com.beans.Member" /> </set> </class> <class name="com.beans.Member" table="MEMBER"> <id name="id" type="int" column="MEMBER_ID"> <generator class="assigned"/> </id> <property name="name"> <column name="NAME" />

Page 14: Hibernate handout

</property> <property name="phone"> <column name="PHONE" /> </property> <property name="salary"> <column name="SALARY" sql-type="numeric(12,2)"/> </property> <many-to-one name="group" column="group_id" class="com.beans.Group" /> </class></hibernate-mapping>

Example:5:ManyToManyEmployee.javapackage com;import java.util.*;

public class Employee { private int id; private String name; private Map benefits;

public Employee() { }

public void setId(int i) { id = i; }

public int getId() { return id; }

public void setName(String s) { name = s; }

public String getName() { return name; }

public void setBenefits(Map m) { benefits = m; }

Page 15: Hibernate handout

public Map getBenefits() { return benefits; }}Benefit.javapackage com;public class Benefit { private int id; private int cost;

public Benefit() { }

public Benefit(int c) { cost = c; }

public void setId(int i) { id = i; }

public int getId() { return id; }

public void setCost(int i) { cost = i; }

public int getCost() { return cost; }}EmployeeClient.javapackage client;import java.io.*;import java.util.*;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.Benefit;import com.Employee;

public class EmployeeTest {

public static void main(String [] args) {

try { SessionFactory sf=new

Configuration().configure().buildSessionFactory(); //This particular statement is used for reading hibernate.cfg.xml and prepare hibernate for use.

Session session=sf.openSession();

Employee sp = new Employee(); Employee sp3 = new Employee();

Page 16: Hibernate handout

sp.setName("John Doe"); HashMap p = new HashMap(); p.put("health", new Benefit(200)); p.put("dental", new Benefit(300)); sp.setBenefits(p);

sp3.setName("Jim Smith"); sp3.setBenefits(p);

session.save(sp); session.save(sp3); session.flush();

Employee sp2 = (Employee)session.load(Employee.class, new Integer(sp.getId()));

Map p2 = sp2.getBenefits(); System.out.println(((Benefit)p2.get("health")).getCost()); System.out.println(((Benefit)p2.get("dental")).getCost());

session.close(); } catch (Exception e) { e.printStackTrace(); } }}

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">

<!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration>

<session-factory><property name="connection.username">sa</property><property name="connection.url">

jdbc:hsqldb:hsql://localhost:8887</property><property name="dialect">

org.hibernate.dialect.HSQLDialect</property><property name="myeclipse.connection.profile">

org.hsqldb.jdbcDriver</property><property name="show_sql">true</property><property name="format_sql">true</property><property name="connection.driver_class">

org.hsqldb.jdbcDriver</property> <property name="hibernate.hbm2ddl.auto">create</property><mapping resource="Employee.hbm.xml" />

</session-factory>

Page 17: Hibernate handout

</hibernate-configuration>

Employee.hbm.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping package="com"><class name="Employee"

table="employee"><id name="id" unsaved-value="0">

<generator class="increment"/></id>

<map name="benefits" table="employee_benefit" cascade="all">

<key column="parent_id"/><index column="benefit_name" type="string"/><many-to-many column="benefit_id" class="Benefit"/>

</map><property name="name" type="string"/>

</class><class name="Benefit"

table="benefit"><id name="id" unsaved-value="0">

<generator class="increment"/></id><property name="cost" type="int"/>

</class></hibernate-mapping>

Example:6:TransactionExEmployee.javapackage com.hibernate;

public class Employee {private int eid;private String ename;private String edepartment;private String edesignation;public String getEdepartment() {

return edepartment;}public void setEdepartment(String edepartment) {

this.edepartment = edepartment;}public String getEdesignation() {

return edesignation;}public void setEdesignation(String edesignation) {

this.edesignation = edesignation;}public int getEid() {

Page 18: Hibernate handout

return eid;}public void setEid(int eid) {

this.eid = eid;}public String getEname() {

return ename;}public void setEname(String ename) {

this.ename = ename;}

}EmployeeClient.javapackage client;

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import com.hibernate.Employee;

public class EmployeeClient {

public static void main(String[] args) {

SessionFactory sf=new Configuration().configure().buildSessionFactory();

Session s=null;Transaction tx=null;try{s=sf.openSession();

tx=s.beginTransaction();

Employee emp1=new Employee();emp1.setEid(100);emp1.setEname("ABC");emp1.setEdepartment("LKM");emp1.setEdesignation("Software Engineer");s.save(emp1);

Employee emp2=new Employee();emp2.setEid(101);emp2.setEname("XYZ");emp2.setEdepartment("JAVA");emp2.setEdesignation("Senior Software Engineer");s.save(emp2);

Employee emp3=new Employee();emp3.setEid(101);emp3.setEname("PQR");emp3.setEdepartment("ORACLE");emp3.setEdesignation("Software Engineer");s.save(emp3);

Page 19: Hibernate handout

tx.commit();}catch(Exception e){

tx.rollback();System.out.println("Problem is:"+e);

}}}

Hibernate.cfg.xml<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property><property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:8887</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="dialect">org.hibernate.dialect.HSQLDialect </property> <property name="hibernate.hbm2ddl.auto">create</property>

<mapping resource="employee.hbm.xml"/> </session-factory>

</hibernate-configuration>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">

<hibernate-mapping> <class name="com.hibernate.Employee" table="employeetransaction">

<id name="eid" type="int" unsaved-value="0"><generator class="assigned"/>

</id><property name="ename" /><property name="edepartment"/><property name="edesignation"/>

</class></hibernate-mapping>

Page 20: Hibernate handout

Example:7:HQLExample(Select query)Employee.javapackage com.hibernate;

public class Employee {private int eid;private String ename;private String edepartment;private String edesignation;public String getEdepartment() {

return edepartment;}public void setEdepartment(String edepartment) {

this.edepartment = edepartment;}public String getEdesignation() {

return edesignation;}public void setEdesignation(String edesignation) {

this.edesignation = edesignation;}public int getEid() {

return eid;}public void setEid(int eid) {

this.eid = eid;}public String getEname() {

return ename;}public void setEname(String ename) {

this.ename = ename;}public String toString()

Page 21: Hibernate handout

{return eid+" "+ename+" "+edepartment+" "+edesignation;

}}EmployeeClient.javapackage client;

import java.util.ArrayList;import java.util.Iterator;

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

import com.hibernate.Employee;

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

SessionFactory sf=new Configuration().configure().buildSessionFactory();

Session s=null;s=sf.openSession();String str="from Employee trans";

ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}}

}

Hibernate.cfg.xml<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property><property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:8887</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="dialect">org.hibernate.dialect.HSQLDialect </property>

Page 22: Hibernate handout

<property name="hibernate.hbm2ddl.auto">update</property>

<mapping resource="employee.hbm.xml"/> </session-factory>

</hibernate-configuration>

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">

<hibernate-mapping> <class name="com.hibernate.Employee" table="transaction">

<id name="eid" type="int" unsaved-value="0"><generator class="assigned"/>

</id><property name="ename" /><property name="edepartment"/><property name="edesignation"/>

</class></hibernate-mapping>

HQL1.Hibernate Query Language or HQL for short is extremely powerful query language. 2.HQL is much like SQL  and are case-insensitive, except for the names of the Java Classes and properties.3. Hibernate Query Language is used to execute queries against database.4. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application.5. HQL is based on the relational object models and makes the SQL object oriented. 6.Hibernate Query Language uses Classes and properties instead of tables and columns

Advantages of HQL:1.Representing SQL queries in form of Objects: HQL allows you to write and run the SQL queries using objects. Thus your object oriented code more readable and homogeneous.

2. Ready made resultset Objects: When hibernate enabled applications run the HQL, the result that u get is a ready-made object ready to be used and thus eleminating the need to first create an object and then populate it using the query result set.

3. Support for Advance Features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, Avis) and grouping, Ordering, Sub queries and SQL function calls.

Page 23: Hibernate handout

4. Database Independency: Queries written in HQL are database independent (If database supports the underlying feature).

5. SubQuery Support: HQL also supports sub queries in case the underlying database supports it.

Select with where clause1. String str="from Employee trans where trans.eid=103";

ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}

Select with and logical operator2. String str="from Employee trans where trans.eid=101 and trans.edepartment='LKM'";

ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}

Select with between operator3. String str="from Employee trans where trans.eid between 100 and 101";

ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}

Page 24: Hibernate handout

Select with in operator4. String str="from Employee trans where trans.eid in (100,104)";

ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}

Select with function lower5. String str="from Employee trans where lower(trans.edepartment)='java')";

ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}

Select working like a prepared statement(Dynamic SQL Statement)6. String str=" from Employee trans where edepartment=? and edesignation=?";

ArrayList l=(ArrayList)s.createQuery(str).setString(0,"JAVA").setString(1,"SSE").list();

Iterator it=l.iterator();while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);}

Select with order by clause

7. String str=" from Employee trans order by trans.edepartment asc"; ArrayList l=(ArrayList)s.createQuery(str).list(); Iterator it=l.iterator();

while(it.hasNext()){

Employee pd=(Employee)it.next(); System.out.println(pd);

}

Update query8. String str="update Employee trans set trans.edepartment='ORACLE'where trans.eid=103 ";

int l=s.createQuery(str).executeUpdate(); System.out.println("Record updated"+l);

Using select in SQL Format

Page 25: Hibernate handout

9. String SQL_QUERY ="Select trans.eid from Employee trans"; Query query = s.createQuery(SQL_QUERY); Iterator it=query.iterate(); while(it.hasNext()) { System.out.println(it.next()); } }

Deleting a record from table10. String str ="delete from Employee trans where trans.eid=103";

int l=s.createQuery(str).executeUpdate(); System.out.println("Record deleted"+l);

Using aggregate function min11. String SQL_QUERY ="Select min(trans.eid) from Employee trans";

Query query = s.createQuery(SQL_QUERY); Iterator it=query.iterate(); while(it.hasNext()) { System.out.println(it.next()); }

Using annotations in hibernate1. In hibernate, database mappings are defined in XML

mapping files. You can end up with a considerable number of Hibernate mapping files. Alternatively you can use tools to generate mapping files from javadoc-style annotations.

2. Using annotations, you can get rid of mapping files. All the information will be entered directly in the java classes in the form of annotations.

3. For annotations, you require hibernate3.2 and java5.You also require hibernate-annotations.jar and java persistence API ejb3-persistence.jar.

4. For obtaining Hibernate Session Factory: use sessionFactory = new AnnotationConfiguration().buildSessionFactory();

5. Now we won’t be using any hbm.xml file. We used to give the information about POJO classes in hbm.xml and the information about hbm.xml is in hibernate.cfg.xml file. Since there is no hbm.xml file, how to provide information about POJO in hibernate.cfg.xml. For this purpose, we need to use: <mapping> element with one attribute class specifying the name of POJO.

6. You need to import the package javax.persistence.* in the POJO.

List of Annotations1.@Entity=annotation declares the class to be persistent

Page 26: Hibernate handout

2.@Id= annotation lets you indicate which property is the unique identifier for this class.3.@Transient= any property will be assumed to be persistent unless you tell it otherwise by using the @Transient annotation4. Automatically generating primary key=@Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; }5.@Table=annotation used for specifying the name of the table. @Table(name="Employee")6.@Column=annotation used for specifying the name of the column. @Column(name="Employee_name") @Column(name="Employee_name", length=80, nullable=true)

Example:8:AnnotationsEmployee.javapackage com.hibernate;

import javax.persistence.*;@Entity@Table(name="annotations")public class Employee {

@Id@Column(name="id")Integer id;

@Column(name="name")String name;

public Integer getId() {return id;

}public void setId(Integer id) {

this.id = id;}public String getName() {

return name;}public void setName(String name) {

this.name = name;}

}EmployeeClient.javapackage client;

Page 27: Hibernate handout

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;

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

SessionFactory sf=new AnnotationConfiguration().configure().buildSessionFactory();

Session s=sf.getCurrentSession();Transaction tx=s.beginTransaction();AnnotationPOJO an=new AnnotationPOJO();an.setId(new Integer(7));an.setName("jp");s.save(an);tx.commit();System.out.println("Record inserted

successfully)");s.close();

}}

Hibernate.cfg.xml<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property><property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:8887</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="dialect">org.hibernate.dialect.HSQLDialect </property> <property name="hibernate.hbm2ddl.auto">create</property>

<mapping class="com.hibernate.EmployeeClient"/> </session-factory>

</hibernate-configuration>

Note: Make sure that hibernate-annotations.jar, ejb-persistence.jar and

Page 28: Hibernate handout

Hibernate-commons-annotations.jar is there in the build path.