-Hibernate is persistence framework which is used to implement persistence Operations or Data base operations.
-Hibernate framework was implemented by RedHat
-Architect of Hibernate is Gavin king.
-Hibernate is ORM(Object Relational Mapping) tool and is best among all other Persistence frameworks like Ibatis, TopLink, JDO etc.
-Hibernate can be implemented either with XML approach (hibernate core)or Annotation approach (Hibernate Annotions).
JDBC Specification is given by SUN and is implemented by various Database vendors
Hibernate is implemented on the top of JDBC Technolongy i. e. you can use Hibernate API Which internally uses JDBC to contact Database.
When you wrie the jDBC code for implementing database operations, you need to perform the following:
try{
Load the Driver Class
Get the connection
Prepare the SQL statement(***)
Create the JDBC statement
Submit the SQL statement to DB.
Process the Results(***)
}catch(Exception e){}
Finally{
Clean the Resources
}
In the above code, more statements(1,2,4,5,7)are common across multiple JDBC Programs. This gives you the code duplication proble.
In JDBC Java Developer is responsible to:
Generate primary keys.
Write SQL statements.
Clean the resources.
Process the Results.
lmplement batch updates.etc
1)Hibernate system is responsible for taking the connectios, creating statements and releasing the resources.
Ex:
Customer cut= new customer(“sri”, “sri@jlc”, 1234)
session. Save(cust);
customer cust= session. Lod(customer. Class, 99
2)Hibernate system is responsible for generating SQL queries which are well – tuned terms of performance.
3)Hibernate system is responsible for generating the value required for primary key columns.
4)Hibernate provides many built- in primary key generation algorithms and also supports to
Implement custom primary key generation algorithms
5) Hibernate supports various mapping
1) simple mapping
2) collection mapping
3) lnheritance mapping
a. Table per sub class mapping
b. Table per class mapping
c. Table per concrete class mapping
4) Association Mapping
a. one- to –one Mapping
b. one to – Many Mapping
c. many- to - Many Mapping
5) other mappings
6) Hibernate supports two ways to manage connection
a.Dreiver Manager connections
b. Data source connection(*)
7Hibernate supports two ways to manage Transactions
a.JDBC Transactions
b. JTA Transactions
8) Hibernate has in - built support for Batch Updates
9)Hibernate provides various caching mechanism.
10)Hibernate provides vrious Query Languages:
a. HQL(*)
b. QBC(*)
c. QBE
d. Native SQL
e. Named SQL
11)Hibernate system uses many persistent best ractices and forces the developer to use them for better performance
steps to develop First Hibernate core Exampe in Eclips
1)create the java project with the name: Lab1
2)Add all hibernate core(3.1) jars to project build path.
3)copy hibernate. Cfg. Xml to src folder.
Note: hibernate . cfg. Xml is called Hibernate configuration Document where you can specifying the Database details.
4) consider the table called customers:
DROP DATABASE jlcindiadh;
CREATE DATABASE jllciindiadb;
USE jlcindiadb;
CREATE TABLE customers(
cid int primary key auto –increment, cname VARCHAR(15),
email AVRCHAR(15), bal double);
5)Crate a package called com. Jlcindia. Hibernante ant write the following
a. Hibernate persistence class i.e. customer. Java
b.Hibernate Mapping document i.e customer. Hbm. Xml to map your table with persistence class
a. Lab 1A. java
b. Lab1B. java
Package com. Jlcindia hibernate ;
//Import HERE
public class customer{
private int cid;
private string cname
Private string email;
private long phone;
Private Timestamp tstamp;// java. Sql. Timestamp
Public customer(){}
Public customer(string cname, string email, long phone)
This. Cname=cname;
this. email = email;
This. phone= phone;
}
//setters and Getters
}
4). Customer. Hbm.xml
/id
hibernate-mapping
5. hibernate.cgf.xml
hibernate-configuration
session-factory
property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver
/property
property name=”hibernate.connection.url”>
Jdbc:mysql://localhost:3306/jlcindiaadb
/property
property name=”hibernate.connection.username”root
/property
property name=hibernate.connection.password”>srinivas/p>
property name=”dialect
Org.hibernate.dialect.MySQLDialect
/property
property name=”show_sql”true/property mapping
Resourse=”com/jlcindia/hibernate/customer.hbm.xml”/>
/session-factory
hibernate-configuration
6. CHibernateUtil java
Package com .jlcindia. hibernate;
import org. hibernate.*;
Import org. hibernate. Cfg.*;
/*
Public class CHibernate Util.{
Static sessionFactory factory;
static{
try{
Configuration cfg= new configuration();
Cfg= cfg. Configure();
Factry= cfg. buildsessionFactory();
}catch (Exception e){e. printstack Trace();}
public static sessionFactory getsessionFactory(){
return factory;
}
Steps to develop First Hibernate Annotation Example in Eclippse
1) create the java project with the name: Lab2
2)Add all hibernate Annotation(3.2) jars to prject build path.
3 ) copy hibernate . xml. Src f older. Note: hibeenate
cfg. .xml called hibernate configuration Document where you cun specifing the Database details.
4)consider the table called customers
DROP DATABASE jlcindiadb;
CREATE DATABASE jlcindiadb;
USE jlcindiadb;
CREATE TABLE customers(
cid int primary key auto- increment,
cname YARCHAR(15),
email VARCHAR(15) phone VARCHAR(15),
city VARCHAR(15), bal double);
5)create a package called com. Jlcindia. Hibernate and
write the following
a. hibernate persistence class i.e. customer. java
6) write the following hibernate client code under package com. Jlcindia. Hibernate.
a. Lab2 A. java
b. Lab2B. java
Step to devel op First Hibernate Annotation Exmple in Eclipse
1) create the java project with the name: Lab2
2)Add all hibernate. Annotation(3.2) jars to project build path.
3) copy hibernate. C fg.xml to src folder.
Note: hibernate. Cfg. xml is called Hibernate cofiguration Document where you can specifing the Database details.
4)consider the table called customers
DROP DATABASE jlcindiadb;
CREATE DATABSE jlcindiadb;
USE jlcindiadb;
CREATE TABLE customers(
cid int primary key auto - increment,
cname VARCHAR(15),
email VARCHAR(15), phone VARCHAR(15),
city VARCHAR(15); bal double);
5)create a package called com. Jlcindia. hibernate and write the following
Hibernate persistence class i.e. customer. java
6) write the following Hibernate client code under
Package com. Jlcindia. hibernate
a. Lab2A. java
Lab2B. java
Lab2: Files required
Questions
Q1) How many instance will be created for the persistence class with the following client code with Hibernate Core?
Configuration cfg=new Configuration();
Cfg=cfg.configure();
Ans: As per above code,0 objection will be created
Q2) How many instances will be created for the persistence class with the following client code with Hibernate Core?
Configuration cfg=new Configuration();
Cfg=cfg.configure();
Session Factory factory=cfg.build Session Factory();
Ans: 3 objects will be created using default constructor for the sreflection process at the time of creating the Session Factory object.
Q3)How many instance will be created for the persistence class
With the following client code with Hibernate Core?
Configuration cfg=new Configuration ();
Cfg=cfg.configurue();
Session Factory factory=cfg.built Session Factory();
Session session=factory.open Session()
Tx=session.begin Transaction();
Customer c1=new Customer(“sd”,”sd@jlc”,1234,”Blore”
);
Session.save(c1);
Customer c2=new Customer(“ds”,”ds@jlc”,4321,”Blore”)
;
Session.save(c2);
Ans: As per above code,2 objects will be created with argumented constructor but at the time of creating the Session
Factory object,3 objects will be created using default constructor for the reflection process.
Q4) How many instances will be created for the persistence class with the following client code with Hibernate Annotation
Annotation Configuration cfg=new Annotation Configuration();
Cfg=(Annotation Configuration)cfg.configure();
Session Factory factory=cfg.build SessionFactory();
Ans:1 object will be created using default constructor for the reflection process at the time of creating the session Factory objection
Q5) How many instances will be created for the persistence class with the following client code with the Hibernate Annotation?
Ans: As per above code,2 objects will be created will be created with argumented constructor but at the time of creating the Session Factory object,1 object will be created using default Constructor for the reflection process
Q6)What will happen when Ispecify the field name wrongly with mapping document or Annotation?
Ans:Unknown colum’cname1’in ‘field list’
Hibernate Mappings
Hibernate supports various mapping styles:
Simple Mapping
Collection Mapping
Inheritance Mapping
Table per sub class mapping
Table per class mapping
Table per class mapping
Association Mapping
a.One-to-One Mapping
b.One-to-Many Mapping
c.Many-to-Many Mapping
5) Other mappings
Simple Mapping
When you map your Hibernate persistence class
W ith simple data types like string, primitives,wrappers, Date etc with the corresponding table columns then it is called as simple Mapping.EX:
Public class customer{
Private int cid;
private string cname;
private string email;
}
with XML:
For primary key property, use id ocomposite-id tag.
EX:
id name=” cid” column=” cid” type=” int”
For other simple properties, use propertytag.
property name=” cname
property name=” email” column=” email
property name=” phone” column=” phone
Type=” long”/
Java Learning Center.docx
With Annotati
you need to use following Annotations for persistence class
@ Entity
@ Table(name=” customers”)
Class customer{…}
you need to use following Annotations for primary key field
@ld
@column(name=” cid”)
Private int cid” //p.k
you need to use following Annotations for other simple filds
@column(name=” cname”)
private string cname;
Collection Mapping
when you map your Hibernate persistence class with collection data types like array, Lis, set,
Map then you have to use collection mapping
Example using Hibernate core(Lab3)
A) Persistence class
class student{
int sid;//p.k
string sname;
String dob ;
String qualification;
string[]courses ;
List stringe mails:
List lnteger marks;
Set Long phones;
map string, Long refs;
D)Client code
string []crs={“ java, JDBC”, JSP”};
List string ems= new ArrayListstring[];
ems.add(“aa@jlc”);
ems.add(“aa@jlc”);
mks.add(“100);
SetLongphs=new HashsetLong[];
phs.add(new Long(1111));
Map string,Long refa= new HashMapstring,Long[];
refs. Put(“AAA”, new Long(111));
student stu=new student(“sri”,10-10-10”, Msc”, crs,ems, mks, phs, refs);
sesson. (stu);
D)Mapping Document
hibernate-mapping package=”com.jlcindia. hibernate
class name=” student” table=” mystudents”)
id name=” sid” type=” int” column=” sid”
generator class=” increment”/>
/id>
property name=” sname”/
property name=” dob”/
property=” qualification” column=”quail/
array name=” courses” table=” courses”
key column=”sid”/
index column=”idx”/
element column=”cname” type=” string”/
/array
list name=” emails” table=” emails”
key column=”sid”/
index column=” idx”/
element column=” email” type=” string”/
/array
list name=” emails” table=” emails
key column=”sid”/
index column=” idx”/
element column=” email” type=” string”/
/list
bag name=” marks” table=” marks
key column=”sid”/>
element column=”marks” type=” int
/bag
set name=” phones” table=” phones”
key column=” sid”/
element column=” phone” type=”long
/set
map name=” refs” table=” refs”
key column=” sid”/
index column=” rname” type=”string”/>
element column=” rphone” type=”long”/
map /class /hibernate- mapping/p>
5. hibernate. Cfg.xm
update/property>
Example using Hibernate Annotation(Lab4):
A)persistence class
@Entity
@Table(name=” mystudents”)
public class
@ld
@GeneratedValue(strategy=GenrationType. AUTO)
@column(name=”sid”)
private int sid;//p.k
@column(name=”sname
Private string sname;
@column(sname=” dob;)
Private string dob;
@column(sname=” quli”)
Private string qualification;
@collection ofElements
@Join Table(name=” courses”, join Column =@Join Column(name=”sid”))
@lndex Column (name=” idx”)
@column(name=”cname”)
private string[] courses;
@collection OfElements
@join Table(name=” emails””, join Colummns=@join Column(name=” sid”)
@lndex Column(name=”idx”)
@Column(name=” emailld”)
Private Liststring emails;
@collection ofElements
@JoinTable (name=”marks”, join Columns=@column(name=”sid”))
@column(name=” marks”)
Private Listlntegermarks;
@collectionofElements
@join Table(name=”phones”, joincolumns=@Joincolumn(name=” sid))
@column(name=” phoneNO”)
Private setLonghones
@collectionofElements
@Join Table(name=” refs”,joincolumns=”@Joincolumn(name=”sid”))
@column(name=” rphone”)
private Mapstring Long>refs;
}
Inheritance Mapping
When multiple Entities are inheritance relationship then use Inheritance Maping.
You can implement Inheritence Mapping in 3 ways
Table per sub class mapping
2. Table per class Mapping
3. Table per concrete class mapping
Consider the following JPA Entities with inheritance relationship.In mystudents.
1) Table per sub class mapping
In this mapping,you needto take one table per one sub Class.
Student is the main super class which will have the master table called mystudents.
Ever subclass will have its own table.
When you save student class object then
o Only one record will be inserted in mystudents
When you save Current Student class object then
o One record will be inserted in mystudents
o One record will be inserted in cstudents
When you save Old Student class object then
o One record will be inserted in mystudents.
o One record will be inserted in ostudents
When you save Weekday Student class object then
o One record will be inserted in mystudents
o One record will be inserted in cstudents
o One record will be inserted in wdstudents
When you save WeekendStudent class object then
o One record will be inserted in mystudents.
o One record will be inserted in cstudents
o One record will be inserted in westudents
Example with hibernate Core (Lab 5)
B)Hibernate Persistance Classes
1) Student.java
Public class Student {
Private int sid;
Private String sname;
Private String city;
Private String stat;
Private double totalfree
}
2)Current Student.java
Public class Current Student extends Student {
Private double feebal;
Private String timings;
Private String branch;
}
4)WeekdayStudent.java
Public class Weekday Student extends Current Student {
Private String qualification;
Private String percentage;
Private int you;
}
5)Weekends Student.java
Public class WeekendStudent extends CurrentStudent {
Private String wcompany;
Private String wcemail
Private double wctc;
}
C)Mapping Document
class name=”Student”table=”mystudents”
id name=”sid”column=sid”type=”int”
generator class=”increment”/
/id
property name=”sname”/
property name=”city”/
property name=”status”/
name=”totalfee”type=”double”/
joined-subclass name=”CurrentStudent”table=” cstudents”
key column=”sid”/
property name=”feebal”type=”cstudents”
property name=”timing”/
property name=”branch”/
joined- subclass name=” weekday student” table= wdstudents”
key column=”sid”/
property name =” qualification”
property name=” percentage” /
property name=” yoe” type=”int”?
/joined - subclass
Example with Hibernate Annotation
B) Hibernate persistence classes
1)student. java
@Entity
@Table(name=” mystudents”)
@lnheritace(strategy=lnheritance Type. JOINED)
Public class student{
}
2)current student.java
@Entity
@Table(name=” cstudents”)
@ prima ry KeyJoinColumn(name=”sid”)
Public class currentstudent extendent{
}
3.oldstudent.java
@Entity
@Table(name=”ostudents”)
@primarykeyJoincolumn(name=”sid”)
public class currentstudent extends student{
…..
}
4.weekday student. java
@Entity
@Table(name=” wdstudents”)
@primarykeyJoinColumn(name=”sid)
Public class weekdaystudent extends current student
….
}
5)weekday student . java
@Entity
@Table(name=” westudents”)
@primarykeyJoinColumn(name=”sid”)
Public class weekendstudent extends currentstudent{
….
}
Note:In the case of Table per sub mapping,
Use the following for super class
@lnheritance(strategy= lnheritance Type. JOINED)
Use the following for all the sub class
@primarykeyJoinColumn(name=”sid”)
2) Table per class mapping
1)student. Java
public class student {
Private int sid;
private string sname;
Private string city;
private string status;
private double totalfee;
….
}
In this mapping you need to take only one table for all the super and sub class.
It is also called as single Table Mapping.
Example With Hibernate core(Lab7)
B)Hibernate persistence class
2)currentstudent. Java
3)oldstudent.java
4 )weekdaystudent. Java
C)Mapping Document
Example with Hibernate Annotation(Lab8)
B)Hibernate persistence class)student
1.student. java
2)current student. java
3)oldstudent.java
4)weekday student. Java
5)weekendstudent. Java
7. weekend student
3)Table per concrete class mapping
In this mapping , you need to take one table for one concrete class.
When you save student class object then only one record will be inserted in mystudents,1.
When you save currentstudent class object then only one record will be inserted in cstudents1.
When you save oldstudent class object then only one record will be inserted in ostudents1.
When you save weekendstudent class object then only one record will be inserted in wdstudents1.
When you save weekendstudent class object then only one record will be inserted in westudent1
A)Tables required
1)mystudents
Example with Hibernate core (Lab9)
B ) Hibernate persistence class
1)student. java
2)currentstudent. Java
3)oldstudent.java
4)weekendstudent. java
5)weekendstudent. java
C)Mapping Document
B)Hibernate persistence class
1)student. java
2)currentstudent. Java
3)oldstudent. Java
4)weekday student.java
5)weekendstudent. Java
Note:
o In the case of Table per concrete class mapping
o Use the following for . super class
@Entity
@Table
@Inheritance(strategy= Inheritance Type. TABLE-PER- CLASS
o Use the following for the supper class and all the sub class
@Etity
@Table(name=” cstudents”)
Don’t specify the primary key generation for sid.
o You set the sid value to all the objects in the client code.
o Don’t save all types of student class object in one session.
11.weekend student. Java
package com. jlcindia. hibernate;
import javax. Persistence.*”
@Entity
@Table(name=” westudents1”)
public class weekendstudent extends currentstudent{
private string company;
private string email;
private string ctc;
Public weekendstudent(){
public weekendstudent(string sname, string city, string status,
double totalfee, double feebal, string timings, string branch);
string company, string email, string ctc){
super(sname, city, status, totalfee, feebal, timings, branch){
this. company= company;
this. email= ctc;
}
//setter and Getter
@override
public string tostring(){
return super. tostring()+”, “,+company+”, “,+email+”, “,+ctc;
}
}
Part 2
Association Mapping
If you want to establish the relationship among different persistence classes, then you have to use Association Mapping.
Depending on the cardinality there are 3 types of Association Mapping:
o One to one Mapping
o One to Many Mapping
o Many to Many Mapping
Depending on the Directionality, you can establish tow type of relationship:
o Uni - Directional Relationship
o Bi – Directional Relationship
Cardinality represents number of objects participating in Relationship on both the sides.
Directionality represents whether we can access the Data in one direction only or both the directions.
Ex:
One- one Bi- Directional
o One customer can have one Address and one Address belongs to one customer .
One Many Bi - Directional
o One customer can place Many Orders and one orders placed by one customer.
Many -M any- Bi Directional
o One customer can have Many Accounts and one Account belongs to Many customers.
o One student can join for Many courses and Many students can join for one course.
One to One Uni Directional Mapping
Consider the relationship between Customer and Address.
o one Address One Customer contain.
o One Address belong to One Customer.
A)Tables Required
1) mycustomers
Expample With Hibernate core
B)Hibernate persistence classes
1)customer
public class customer{
…
Address address;
}
2)Address. Java
class Address{
…..
}
C)Hibernate Mapping Document
1)customer.hbm.xml
”
2)Address. hbm. Xml
Ex ample with Hibernate Annotations
B)Hibernatepersistence class
1)customer .java
@Entity
@Table(name=” mycustomers”)
public class customer{
…
@one Toone
@Join column(name=”aid”)
Address address;
2)Address. java
@Entity
@Table(name=” address”)
class Address{
….
}
one to Bi- Directional Mapping:
Consider the relationship between customer and Address.
o One customer contains one Address.
o One Address belongs to one customer
A)Tables Requires
1) mycustomer