You are on page 1of 30

Hibernate 3.

0
1. Features of Hibernate are:1) 2) 3) 4) 5) Automatic primary key generation High performance J2EE integration Object / Relational Mapping Object-Oriented Query Language

2. Advantages of Hibernate:-

1) Hibernate is data base independent, same code will work for all data bases like Oracle, MySQL, SQL
2) 3) 4) 5) 6) Server etc. High Performance Development fast in case of Hibernate because you dont need to write queries. Automatic primary key generation In the xml file you can see all the relations between tables in case of Hibernate. Easy readability. Hibernate Support automatic versioning of rows but JDBC not.

3. Disadvantages of Hibernate:1) Everything is an object. If you need only a portion of data (say, for a search), you would still have to retrieve the object. 2) Sometimes debugging and performance tuning becomes difficult. 3) For complex data, mapping from object to tables and vice versa reduces performances. 4) It is something difficult for the beginners. 4. First application in Hibernate:1) 2) 3) 4) 5) First we create a hibernate cfg.xml file Write first java persistence class. Mapping the Emp Object to the Database emp table SessionProvider is created for creating the object of session. Main java class

1) First application in Hibernate


It is a first application which persist data into database: Step 1:- First we create a hibernate.cfg.xml file: Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. // 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="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">password</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <mapping resource="Emp.hbm.xml"/> </session-factory> </hibernate-configuration>

Hibernate 3.0
Step 2:write first java persistence class.
// Emp.java

package r4r; public class Emp { int id; String name,job; int salary; public Emp() { super(); } public Emp(String name, String job, int salary) { super(); this.name = name; this.job = job; this.salary = salary; } 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 getJob() { return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } }

Step:3 // Mapping the Emp Object to the Database Emp table The file Emp.hbm.xml is used to map Emp Object to the Emp table in the database. Here is the code for Emp.hbm.xml:
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. <hibernate-mapping> <class name="r4r.Emp" > <id name="id" type="int"> <generator class="increment" /> </id> <property name="name" /> <property name="job" /> <property name="salary" type="int"/> </class> </hibernate-mapping> -->

Hibernate 3.0
Step 4:// SessionProvider is created for creating the object of session. //sessionProvider.java
package r4r; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class SessionProvider { static SessionFactory factory; static { Configuration cfg=new Configuration().configure(); factory=cfg.buildSessionFactory(); } public static Session getSession() { return factory.openSession(); } }

Step5:// main java class


//PersistTest.java package r4r; import java.util.*; import org.hibernate.Session; import org.hibernate.Transaction; public class PersistTest { public static void main(String[] args) { Scanner in=new Scanner(System.in); Session session=SessionProvider.getSession(); Transaction t=session.beginTransaction(); while(true) { System.out.println("Enter Name:"); String n=in.nextLine(); System.out.println("Enter Job:"); String j=in.nextLine(); System.out.println("Enter Salary:"); int s=in.nextInt(); in.nextLine();// to remove unread newline character. Emp e=new Emp(n,j,s); session.save(e); System.out.println("want to persist more objects yes/no?"); String ans=in.nextLine(); if(ans.equals("no")) break; } t.commit(); session.close(); System.out.println("successfully persisted."); } }

Commonly used classes and interfaces exposed by hibernate for application developer: Configuration: - Configuration object is used by the hibernate to stored configuration information in object form.Configuration information data is required by hibernate to connect to a database and information of classes that are to be managed by hibernate.

Hibernate 3.0
SessionFactory:- It is a factory class which is used by application developer to create session.A part from this it can also be used to manage second level cache. Session:-This is a main interface throw which application eveloper interact. This interface provides method for persistence object, creating transaction and query objects for each user a different session is provided. Transaction:-This interface is used by application developer to transact execution query. Query: - This interface is used by he application developer to execute HQL query. HQL is object versions of sql used by hibernate.

A simple select program of Hibernate :1- Create hibernate.hbm.xml file


<?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="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="Emp.hbm.xml"/> </session-factory> </hibernate-configuration> 2- Create Emp.java class:- Show package r4r; public class Emp { int id; String name,job; int salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; }

in a Message Box using Validation Summary

Hibernate 3.0
public void setId(int id) { this.id = id; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } }

Show in a Message Box using Validation Summary 3- Create Emp.hbm.xml file:<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- r4r.co.in. --> <hibernate-mapping> <class name="mypack.Emp"> <id name="id" type="int"></id> <property name="name"></property> <property name="job"></property> <property name="salary" type="int"></property> </class> </hibernate-mapping>

4- Create Session provider class // SessionProvider.java

package r4r; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class SessionProvider { static SessionFactory factory; static

Hibernate 3.0
{ Configuration cfg=new Configuration().configure(); factory=cfg.buildSessionFactory(); } public static Session getSession() { return factory.openSession(); } }

5- Create a main class // SelectTest.java


package r4r; import java.util.Scanner; import org.hibernate.Session; import org.hibernate.Transaction; public class SelectTest { public static void main(String rr[]) { Session session=SessionProvider.getSession(); Transaction t=session.beginTransaction(); // List<Emp> list=new List<Emp>; Scanner in=new Scanner(System.in); System.out.println("enter id:-"); int id=in.nextInt(); Emp e=(Emp)session.load(Emp.class,id); System.out.println("followin records are fetched:-"); System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getJob()+"\t"+e.getSalary()); t.commit(); session.close(); } }

Some Important Methods Of Hibernate:


save():-

method of Session interface is used to persist object. public void save (Object o);

delete():is used to remove a persistent object. public void delete(Object o);

refresh():is used to Synchronized the state of a persistaent logc to the database. public void refresh(Object o);

beginTransaction:is used to start a transaction. public Transaction begintransaction();

Hibernate 3.0

createQuery:-

is used to obtain query object.Query object is used to run sql query. public query createquery(); etc

ID Generator:-

Id generator is used to auto generate id of objects. Different database support different types of generator. Most commonly used generator that is supported by oracle is: 1-increment 2-sequential

1. increment:- Increment generator uses highest value of primary key increases to generator id value.
Example:- Consider previous example of Student, in which id generator is used as:
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- r4r.co.in. --> <hibernate-mapping> <class name="r4r.Student"> <id name="id" type="int"> <generator class="increment"></generator> </id> <property name="name"></property> <property name="course"></property> </class> </hibernate-mapping>

2-Sequence Generator:- sequence generator uses the sequence define in the database for generating id. Example:- Consider Emp example
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- r4r.co.in. --> <hibernate-mapping> <class name="r4r.Emp"> <id name="id" type="int"> <generator class="sequence"> <param name="sequence">oursequence</param> </generator> </id> <property name="name"></property> <property name="job"></property> <property name="salary" type="int"></property> </class> </hibernate-mapping>

Hibernate Mapping: - There are two types of mapping: 1-Is -A Mapping

Hibernate 3.0
2-Has-A Mapping

1. Is-A Mapping:- Is a relation between persistent object can be implemented in the following three ways1- Table per class Hierarchy 2- Table per subclass 3- Table per class 1- Table Per Class Hierarchy:- In this approach objects of all the classes of a family are mapped to a single table in a database. This table contain field to represent combined data member of all the classes of the family plus an additional fields is used to describe record of the table ,that is, to identified which record of table represent object of which class of the family Advantages of This Approach:- Major advantages of this approach is performance. Because hibernate need to manage to all the classes to the family. Disadvantages of This Approach:1-Table is not normalized 2-Not Null constraint can not be applied non the field representing data member of subclass 2-Table per Subclasses: - In this approach one table for each class of the family is created. Table for the parent class contains field to represenent parent class data member and table for the subclasses contains fields to represent their own data member. Primary key of parent table is used for hierarchy in table for subclasses. Advantages Tables are normalized Not null constraint can be applied

Disadvantages: performance is degraded because to insert and fetched subclasses object .Multiple queries or joins are required Tables are not fully normalized.

3-Table Per Class:- In this approach one table for each class of the family is created. Each table contains fields to represents declared as well as inherited data member of the class. Advantages: Tables are fully normalized. Not null constraint cn be applied on all the table of fields. Better performance.

Disadvantages: Relation of object is losses in the table. This approach s not supported in the all ORM framework.

Has-A- Mapping:- Has-A relation between object can be of following types:1-One-to-One (Unidirectional and bidirectional) 2-One-to-Many (Unidirectional and bidirectional) 3-Many-to-Many (Unidirectional and bidirectional)

Hibernate 3.0

1-One-to-One Mapping:- One to one mapping between object can be implement with the three ways- In case of unidirectional:1- Using primary key-foreign key relation 2- Using same primary Key 3-Using relation table Disadvantages:- This approach can only be used if relation between objects which be one to one .If in future one to one is changed to one to many then this approach went to wrong. 1- Using Primary Key-Foreign Key Relation:- Consider two classes first Address(owned object) and second Person(owner object) .In address there are three fields id, street and city. And in person table it contains id, name, address. Example://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"> <!-- r4r.co.in. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="PkFk.hbm.xml"/> </session-factory> </hibernate-configuration>

//Address.java
package r4r; public class Address { int id; String city,street; public Address() { } public Address(String city, String street) { super(); this.city = city; this.street = street; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street;

Hibernate 3.0
} public void setStreet(String street) { this.street = street; } }

//Person.java package r4r; public class Person { int id; String name; Address address; public Person() { super(); } public Person(String name, Address address) { super(); this.name = name; this.address = address; } 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 Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } //PkFk.hbm.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-mapping> <class name="r4r.Address"> <id name="id" type="int"> <generator class="increment"></generator> </id> <property name="city"></property> <property name="street"></property> </class> <class name="r4r.Person"> <id name="id" type="int"> <generator class="increment"></generator> </id> <property name="name"></property> <many-to-one name="address" class="r4r.Address" column="addressid" unique="true" cascade="all"> </many-to-one> </class>

10

Hibernate 3.0
</hibernate-mapping>

//InsertTest.java
package r4r; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class InsertTest { public static void main(String[] args) { try { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); Transaction t=session.beginTransaction(); Address a=new Address("noida","u.p"); Person p=new Person("name",a); session.save(a); session.save(p); t.commit(); session.close(); System.out.println("successfully inserted"); } catch(Exception e) { System.out.println("exception thrown"); } } }

2-Same Primary Key Mapping:- In this approach owner and owned shared same primary key value. Advantages:- It eliminate the need of foreign key. Disadvantages:1- A special id is generator is required to used id of one object as id of another. 2- If it converted into one-to-many then this approach will not be used. Example://SamePk.hbm.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-mapping> <class name="r4r.Address"> <id name="id" type="int"> <generator class="increment"></generator> </id> <property name="city"></property> <property name="street"></property> </class> <class name="r4r.Person"> <id name="id" type="int"> <generator class="foreign"> <param name="property">address</param>

11

Hibernate 3.0
</generator> </id> <property name="name"></property> <one-to-one name="address" class="r4r.Address" cascade="all"> </one-to-one> </class> </hibernate-mapping>

3-Using Relation Table:- In this approach the relation table is used to manage the relation between obect. Primary key of both objects are used as foreign key in relation table . Advantages:- support one-to-many ,if any time one name has many address then it support it . Disadvantage:- Performance is degraded. Example:- In this approach three tables are used 1- Table for Batch(id,name) 2-Table for Trainer(id,name,fees) 3-Table for Relation(batchid,trainerid)
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-mapping> <class name="r4r.Address"> <id name="id" type="int"> <generator class="increment"></generator> </id> <property name="city"></property> <property name="street"></property> </class> <class name="r4r.Person" table="person3"> <id name="id" type="int"> <generator class="increment"> </generator> </id> <property name="name"></property> <join table="addresses"> <key column="personid"> <many-to-one name="address" class="r4r.Address" cascade="all" column="addressid" unique="true"> </many-to-one> </join> </class> </hibernate-mapping>

2-One-to-Many Mapping:- This type of association relates one entity object to many object of another entity. Example:- Relationship between a department and employee.Many employee can work in a single department. //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">

12

Hibernate 3.0
<!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="listAndBag.hbm.xml"/> </session-factory> </hibernate-configuration>

// Batch.java
package r4r; public class Batch { int id; String time,course,mode; Trainer trainer; public Batch() { super(); } public Batch(String time, String course, String mode,Trainer t) { super(); this.time = time; this.course = course; this.mode = mode; this.trainer=t; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public Trainer getTrainer() { return trainer; } public void setTrainer(Trainer trainer) { this.trainer = trainer; }

} //Trainer.java
package r4r; import java.util.*; public class Trainer { int id; String name; Set<Batch> batches; public Trainer() { super();

13

Hibernate 3.0
} public Trainer(String name) { super(); this.name = name; } 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 Set<Batch> getBatches() { return batches; } public void setBatches(Set<Batch> batches) { this.batches = batches; } }

//sessionProvider.java
package r4r; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class SessionProvider { static SessionFactory factory; static { Configuration cfg=new Configuration().configure(); factory=cfg.buildSessionFactory(); } public static Session getSession() { return factory.openSession(); } }

//PersisTest.java
package mypack; import java.util.*; import org.hibernate.Session; import org.hibernate.Transaction; public class PersistTest { public static void main(String[] args) { Trainer tr=new Trainer("Rama"); Batch b1=new Batch("9 to 11","Core", "w/d",tr); Batch b2=new Batch("12 to 3", "J2ee", "w/e",tr); Batch b3=new Batch("9 to 12", "Hibernate", "w/e",tr); Session s=SessionProvider.getSession(); Transaction t=s.beginTransaction(); s.save(b1); s.save(b2); s.save(b3); t.commit(); s.close(); System.out.println("persisted."); }}

Many-To-Many Mapping:- In order to implement many-to-many bidirectional relation between object.Each participants relation object of the relation contains the properties. One of these object is designed as the owner of the relation and the other is as owned by using inwards attributes of collection mapping. This type of relation relates many objects of an entity to many object of anothe entity. Example:- consider an example of employee and privileges A employee can get many privileges and many employee can get a single privileges.

14

Hibernate 3.0
So here is an many-to-many mapping

Example Of Many To Many Mapping://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"> <!-- R4r.co.in. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="m-to-m.hbm.xml"/> </session-factory> </hibernate-configuration>

//Emp.java
package r4r; import java.util.*; public class Emp { int id; String name,job; int salary; Set<Privilage> privilages; public Emp() { super(); // TODO Auto-generated constructor stub } public Emp(String name, String job, int salary, Set<Privilage> privilages) { super(); this.name = name; this.job = job; this.salary = salary; this.privilages = privilages; } 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 getJob() {

15

Hibernate 3.0
return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public Set<Privilage> getPrivilages() { return privilages; } public void setPrivilages(Set<Privilage> privilages) { this.privilages = privilages; } }

//Privilage.java
package r4r; import java.util.Set; public class Privilage { int id; String name; int cost; Set<Emp> employees; public Privilage() { super(); // TODO Auto-generated constructor stub } public Privilage(String name, int cost, Set<Emp> employees) { super(); this.name = name; this.cost = cost; this.employees = employees; } 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 int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } public Set<Emp> getEmployees() { return employees; } public void setEmployees(Set<Emp> employees) { this.employees = employees; } }

//m-to-m.hbm.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-mapping> <class name="r4r.Privilage">

16

Hibernate 3.0
<id name="id" type="int"> <generator class="increment"></generator> </id> <property name="name"/> <property name="cost" type="int"/> <set name="employees" table="empprivilage" inverse="true"> <key column="privilageid"/> <many-to-many column="empid" class="r4r.Emp"/> </set> </class> <class name="r4r.Emp"> <id name="id" type="int"> <generator class="increment"/> </id> <property name="name"/> <property name="job"/> <property name="salary"/> <set name="privilages" inverse="true" cascade="all" table="empprivilage"> <key column="empid"/> <many-to-many column="privilageid" class="r4r.Privilage"/> </set> </class> </hibernate-mapping>

//Selecttest.java
package r4r; import java.util.Iterator; import java.util.Scanner; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Selecttest { public static void main(String[] args) { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); Scanner in=new Scanner(System.in); System.out.println("enter empid"); int empid=in.nextInt(); Emp emp=(Emp) session.load(Emp.class,empid); System.out.println("employees details"); System.out.println(emp.getName()+"\t"+emp.getJob()+"\t"+emp.getSalary()); System.out.println("following privilages are enjoyed:"); Set<privilage> pr=emp.getPrivilages(); Iterator<privilage> itr=pr.iterator(); while(itr.hasNext()) { Privilage pre=itr.next(); System.out.println(pre.getId()+"\t"+pre.getName()+"\t"+pre.getCost()); } System.out.println("enter privilage id:"); int privilageid=in.nextInt(); Privilage privilages=(Privilage) session.load(Privilage.class,privilageid); System.out.println("following privilage detais:"); System.out.println(privilages.getName()+"\t"+privilages.getCost()); System.out.println("employee benifited are:-"); Set<emp> emp11=privilages.getEmployees(); System.out.println("following employees are benifited: "); Iterator<emp> eitr=emp11.iterator(); while(eitr.hasNext()) { Emp e=eitr.next();

17

Hibernate 3.0
System.out.println(e.getName()+"\t"+e.getJob()+"\t"+e.getSalary()); } session.close(); } }

HQL (Hibernate Query Language):- It is an object based version of SQL, it is used by hibernate to fetch data.Hibernate even provide a criterion API that provide a type safe and object oriented way to retrieve object from database.

Using SQL has following shortcoming: 1- SQL is standarized but it is vendor -dependent features. 2-SQL is designed more specifically to work with relational database tables but not object. To overcome these issues Hibernate introduce its own object oriented query language called Hibernate Query Language(HQL). Advantages Of Using HQL:1- HQL queries are database independent. 2-HQL provide a support for ordering the result persist objects. 3-HQL is more object oriented which makes us write more easily than Sql. 4- HQL support pagination. Step To Execute HQL queries Using Hibernate:The following three steps are required in executeing HQL queries. 1- Obtaining an instance of org.hibernate.Query 2-Customize the Query object 3-Execute the Query Step 1- Obtaining an instance of org.hibernate.Query:A Query instance is obtained by calling Session.createQuery() or Session.getNamedQuery method. The createQuery() method is used to create a new instance of Query for given HQL Query. Step 2- Customize the Query object:After obtaining the query object we may want to customize it by setting query parameter ,cache mode , Flush mode,fetch size ,an upper limit for the result set. Step 3- Execute the Query:After preparing the query object by setting all custom properties we use list(),scroll(),iterate or uniqueResult().

18

Hibernate 3.0
Syntax Of HQL Queries:To fetch the all the object of a type:from classname as Alias ex1- To fetch all the emp object:Query q=Session.createQuery("From Emp e") -2- To fetch only Those object to class which satisfy given condition from classname as Alias where condition ex- To fetch all those employee who earn more 75000/month from Emp e where e.salary>75000 3-To fetch name of all manager select e.name from Emp e where e.job="manager"

Note:HQL queries supports named as well as positioned parameters First Approach:-(positioned parameter):Query q=session.createQuery("select e.name from Emp e e.job=?"); q.setString(1,job); // value of positioned parameter is set. Second Approach(Named parameter):Query q=session.createQuery("from Emp e where e.salary>:salary"); q.setInt("salary",s); Simple Program Of Select in HQL:Step1- Create 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="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="Emp.hbm.xml"/> </session-factory> </hibernate-configuration>

Step2- Create Persitent class //Emp.java

19

Hibernate 3.0
package mypack; public class Emp { int id; String name,job; int salary; public Emp() { super(); } public Emp(String name, String job, int salary) { super(); this.name = name; this.job = job; this.salary = salary; } 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 getJob() { return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } }

//Emp.hbm.xml
?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-mapping> <class name="mypack.Emp"> <id name="id" type="int"></id> <property name="name"></property> <property name="job"></property> <property name="salary" type="int"></property> </class> </hibernate-mapping>

//PersistTest.java
package mypack; import java.util.*; import org.hibernate.Query; import org.hibernate.Session; public class PersistTest { @SuppressWarnings("unchecked") public static void main(String[] args) { Session session=SessionProvider.getSession(); Query q=session.createQuery("from Emp e"); List<Emp> e=(List<Emp>) q.list();

20

Hibernate 3.0
Iterator<Emp> itr=e.iterator(); System.out.println("following data fetched"); while(itr.hasNext()) { Emp emp=itr.next(); System.out.println(emp.getName()+"\t"+emp.getSalary()); } session.close(); } }

Example of Select Program in HQL: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="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="Student.hbm.xml"/> </session-factory> </hibernate-configuration>

Student.java
package mypack; public class Student { int id; String name; String subject; public Student() { super(); } public Student(String name, String subject) { super(); this.name = name; this.subject = subject; } 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 getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; }

}
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->

21

Hibernate 3.0
<hibernate-mapping> <class name="mypack.Student" table="stud"> <id name="id" type="int"> <generator class="increment"/> </id> <property name="name"/> <property name="subject"/> </class> </hibernate-mapping>

//Insert Demo
package mypack; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class InsertDemo { @SuppressWarnings("unchecked") public static void main(String[] args) { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); Query q=session.createQuery("from Student"); List<Student> student=q.list(); Iterator<Student> itr=student.iterator(); while(itr.hasNext()) { Student s=itr.next(); System.out.println(s.getName()); } session.close(); } }

Hibernate Caching:-caching is the facility of storing object temporally in the memory . The purpose of caching to improve the performance by reducing database hits . If same object is required by different session or user then it make sense to fetch them only one and to store them into the cache so that they can provide the cache each time they are requested. Hibernate support caching at two levels:1- First Level Caching 2-Second Level Caching First Level Caching :-(Transactional scope caching):- First level caching is implicitly enable. It is implemented by session. Fist level caching is responsible for storing the object used by user.Object in this cache has transactional scope, once the transaction is completed object of this cache are synchronize to the database and cache is discarded. Second Level Cache (Application Scope caching):- Second level cache is not enable by default. This cache has a application scope, Object in this cache are shared by multiple users. This cache is managed by sessionFactory NOTE:-Hibernate does not provide implementation of Second level caching , it only provide specification how second level cache should be implemented. Third party implementation of second level cache are available:

22

Hibernate 3.0
1- EHCACHE ( Easy hibernate Caching) 2-OSCACHE (Open source caching) Specification Of second Level Cache:- Hibernate Specification says that cache provider must defined block in memory for storing object. I these storing block objects are stored in it. Each block must have name and must have some additional properties. Second level cache is divided into two parts:1- Object cache 2-Query Cache 1-Object Cache: - In object ache, object along with there relation is stored in Simplified Form. 2-Query Cache: - In query cache, Queries are stored along with the ID of fetched object. For the implementation of query cache two reasons are created in memory 1- In first reason query along with the value of parameter to store as key and id of returned object are stored as value. 2- In second region time stamp of query execution is stored. The Purpose of this region is to identified whether result of query is valid or not. Program Of EHCache:Example: This example shows the implementation of EHCache 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">system</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.password">oracle</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.generate_statistics">true</property> <property name="hibernete.ca"></property> <mapping resource="m-to-m.hbm.xml"/> </session-factory> </hibernate-configuration>

m-to-m.hbm.xml:<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. <hibernate-mapping> <class name="mypack.Previlige"> <cache usage="read-write"/> <id name="id" type="int"> <generator class="increment" /> </id> -->

23

Hibernate 3.0
<property name="name"/> <property name="cost" type="int"/> <set name="users" table="empPrevilige" inverse="true"> <key column="previligeId"/> <many-to-many class="mypack.Emp" column="empId" /> </set> </class> <class name="mypack.Emp"> <cache usage="read-write"/> <id name="id" type="int"> <generator class="sequence" > <param name="sequence">keygenerator</param> </generator> </id> <property name="name" /> <property name="job" /> <property name="salary" type="int"/> <set name="previliges" table="empPrevilige" cascade="all"> <cache usage="read-write"/> <key column="empId"/> <many-to-many class="mypack.Previlige" column="previligeId" /> </set> </class> </hibernate-mapping>

ehcache.xml:<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-mapping> <class name="mypack.Previlige"> <cache usage="read-write"/> <id name="id" type="int"> <generator class="increment" /> </id> <property name="name"/> <property name="cost" type="int"/> <set name="users" table="empPrevilige" inverse="true"> <key column="previligeId"/> <many-to-many class="mypack.Emp" column="empId" /> </set> </class> <class name="mypack.Emp"> <cache usage="read-write"/> <id name="id" type="int"> <generator class="sequence" > <param name="sequence">keygenerator</param> </generator> </id> <property name="name" /> <property name="job" /> <property name="salary" type="int"/> <set name="previliges" table="empPrevilige" cascade="all"> <cache usage="read-write"/> <key column="empId"/> <many-to-many class="mypack.Previlige" column="previligeId" /> </set> </class> </hibernate-mapping>

Emp.java:package r4r; import java.util.*; public class Emp { int id; String name,job; int salary; Set<Previlige> priviliges;

24

Hibernate 3.0
public Emp() { super(); } public Emp(String name, String job, int salary, Set<Previlige> priviliges) { super(); this.name = name; this.job = job; this.salary = salary; this.priviliges = priviliges; } 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 getJob() { return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public Set<Previlige> getPriviliges() { return priviliges; } public void setPriviliges(Set<Previlige> priviliges) { this.priviliges = priviliges; } }

Previlage.java:package r4r; import java.util.Set; public class Previlige { int id; String name; int cost; Set<Emp> users; public Previlige() { super(); } public Previlige(String name, int cost) { super(); this.name = name; this.cost = cost; } 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 int getCost() { return cost; }

25

Hibernate 3.0
public void setCost(int cost) { this.cost = cost; } public Set<Emp> getUsers() { return users; } public void setUsers(Set<Emp> users) { this.users = users; } }

SessionProvider.java:package r4r; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class SessionProvider { static SessionFactory factory; static { Configuration cfg=new Configuration().configure(); factory=cfg.buildSessionFactory(); } public static Session getSession() { return factory.openSession(); } } // S2Test.java:package r4r; import java.util.*; import org.hibernate.*; import org.hibernate.cfg.Configuration; import org.hibernate.stat.SecondLevelCacheStatistics; public class S2Test { public static void main(String[] args) { try { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); for(int i=1;i<=2;i++) { Session s=f.openSession(); Date d1=new Date(); Emp e=(Emp)s.load(Emp.class, 52501); Set<Previlige> set=e.getPriviliges(); Date d2=new Date(); System.out.println("query took "+(d2.getTime()-d1.getTime())+ " milliseconds "+i+" time."); System.out.println("Emp Details:"); System.out.println(e.getName()+"\t"+e.getJob()+"\t"+ e.getSalary()); System.out.println("previliges details..."); Iterator<Previlige> itr=set.iterator(); while(itr.hasNext()) { Previlige pr=itr.next(); System.out.println(pr.getId()+"\t"+pr.getName()+"\t" +pr.getCost()); } s.close(); SecondLevelCacheStatistics sts1 = f.getStatistics(). getSecondLevelCacheStatistics("mypack.Emp"); System.out.println("details of Emp cache region:"); System.out.println(sts1); SecondLevelCacheStatistics sts2 = f.getStatistics(). getSecondLevelCacheStatistics("mypack.Previlige"); System.out.println("details of previlige cache region:"); System.out.println(sts2); } }catch(Exception e)

26

Hibernate 3.0
{ System.out.println(e); } } }

Working With Collection In Hibernate:-Collection is widely used in hibernate . Example:-- 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="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="ListCollection.hbm.xml"/> </session-factory> </hibernate-configuration> <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. <hibernate-mapping> <class name="r4r.Songs" table="songs"> <id name="id" type="int"> <generator class="increment" ></generator> </id> <property name="info"/> </class> <class name="r4r.Persons" table="persons"> <id name="id" type="int"> <generator class="increment"></generator> </id> <property name="name"/> <bag name="song" table="songs1" cascade="all"> <key column="personid"/> <many-to-many class="r4r.Songs" column="songid"/> </bag> </class> </hibernate-mapping> package r4r; import java.util.List; public class Persons { int id; String name; List<Songs> song; public Persons() { super(); // TODO Auto-generated constructor stub } public Persons(String name, List<Songs> song) { super(); this.name = name; this.song = song; } -->

27

Hibernate 3.0
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 List<Songs> getSong() { return song; } public void setSong(List<Songs> song) { this.song = song; } } package r4r; public class Songs { int id; String info; public Songs() { super(); } public Songs(String info) { super(); this.info = info; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } } package r4r; import java.util.ArrayList; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class InsertTest { public static void main(String[] args) { try { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); ArrayList<Songs> list=new ArrayList<Songs>(); list.add(new Songs("mast mast laila")); list.add(new Songs("dhink ckika")); Persons p=new Persons("sushant",list); Transaction t=session.beginTransaction(); session.save(p); t.commit(); session.close();

28

Hibernate 3.0
System.out.println("successfully inserted"); } catch(Exception e) { System.out.println(e); } } }

29

Hibernate 3.0

30

You might also like