Hibernate

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 19

Advanced Java

Book1-WCD(Web Component Developer)


----------------------------------
40hrs (20days)
JDBC
Servlet
JSP
XML

Adv Java Book2


--------------
Module:Hibernate & Spring Frameworks[Adv Java Book2]
Duration:40 hrs (20 days)
Today we starting with module Hibernate

Hibernate-20hrs(10 days)
Spring-20hrs(10 days)
Spring Boot-20hrs (10 days)

Hibernate is a Framework??
--------------------------
Framework is semi-developed code which can be customized to develop our application
faster

we dont to develop our application from scratch

we acheive RAD[Rapid Application Development]

****Hibernate is a Database Framework


It saves an object into DB
Employee emp=new Employee(101,'Robert',23000);
Here emp object is stored in heap(temporarily stored)

Object Persistence
------------------
we want to store object state permanently
Employee emp=new Employee(101,"RObert",78900);
session.save(emp);
we are trying save an object in to the database

**Hibernate is a Framework used for Object Persistence in the database.

transient object--->in memory


persistent object--->permenantly stored

Hibernate saves an object into the database

Problem statement:-SAve Employee information???


JDBC,Serialization,XML,EJB-Entity Bean

Object Persistence Mechanisms


------------------------------
1)JDBC:-
-----
application connects to the db via DriverManager/
DataSource[Connection Pooling]

appln fires query using Statement,PreparedStatement, CallableStatement(stored


procedure)
To retrive data ResultSet/RowSet is used

Pros:-
simple to code

Cons:-
-repeated coding
-transaction & concurrency needs to be done manually
-caching & dynamic update require extra efforts

---------------------------------------------------
1)
Connection con=DriverManager.getConnection
(dburl,dbuser,dbpass);
Here conn object will be created & then returned

con.close();//here conn object gets destroyed

2)
DataSource ds=ctx.lookup("myds");
Connection con=ds.getConnection();
Here precreated conn object is returned
....
con.close();//here conn is object is added back to the free pool
----------------------------------------------------

1)simpler syntax for dynamic query


PS executes dynamic query(query which accepts runtime input )
with a simpler syntax
insert into emp values (?,?,?) --->placeholder

2)PreparedStatement executes precompiled queries


frequently required static query is compiled only once & native code is cached &
reused.Hence PS offer better performance than statement

Statement-->compiled 100 times


PS--->compiled once & reused

"select * from emp"(query)---->native db lang


----------------------------------------------------

To fetch data frm ResultSet--->3 objects


Connection,Statement,ResultSet

To fetch data using RowSet--->only Rowset(conn,fire query,data retrive data)

Rowset
1)3-in-1(conn,fire query,data retrive data)
2)Scrollable and updatable is by default
3)also supports disconnected architecture(works on offline data)

Rowset 2 types --->JdbcRowSet (connected architecture)


CachedRowSet(disconnected architecture)

DAO Design Pattern[Data Access Object]


A-->main-->accept empid-->fetch(empid)
print output using rowset

B--->rowset fetch(eid){fetch data thro rowset}


_______________________________________________________

2)Serialization
--------------
Serialization is process of converting object state into a bytestream.
This bytestream can then be stored into file/transfer across network

Pros:-
automated object peristence in a file
[
we just need to pass object to a method writeObject()
class need to implements Serializable
]
Cons:-
object--(oos)-->bytestream--(fos)-->file [slow]
hence not suitable for large scale data

//Marker or Tagging interface


public class Employee implements Serializable{
int empId;
String empName;
double salary;
Address resAddr;

}
public class Address implements Serializable{
String street,city,state,country;
}

Employee emp=new Employee(101,"RObert",78900,new Address(...));


FileOutputStream fos=new FileOutputStream("emp.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(emp);
-----------------------------------------------------------

What is a marker/tagging interface?


It is an empty interface,which does not have any method
whenever any class implements it,the class need not impl any method
MI is used to grant a special permission/feature to its implementing class
_______________________________________________________

3)XML:- Extensible Markup language


----
we can store an object in to an xml file using XMLStreamWriter

file---->sequential manner
db------>tabular manner
xml----->structured manner

emp.dat
-------
101 Robert 78900......

employee.xml
------------
<Employee>
<id>101</id>
<name>RObert</name>
<salary>78900</salary>
</Employee>

Pros:-
stores structured data in a text format[hence best suited for transferring data
between heterogeneous systems]

Cons:-
Not good for large scale data
________________________________________________________
task:-
save a product object into an xml document using XMLStreamWriter

Java Bean -reusable business component


holds the business logic of web application
it can be used again and again within the same application

4)EJB - Entity Bean (manages object persistence automatically)


----------------
EJB- Enterprise Java Bean
3 types of EJB
1)Session Bean [only BL]
2)Entity Bean[persistence code/data access code]
3)Message Driven Bean[message passing]

Entity Bean has 2 types


BMP-BEan managed persistence [persistence code is written by programmer]

CMP-Container Managed Persistence [persistence code is autogenerated]

Pros:- Automated Object Persistence in database


[we dont need to connect to db,fire query]

Cons:-
i)developing EJB is overcomplex[need to implement specific interfaces]
ii)requires Managed Environment [requires Application Server eg:-
JBOSS,WebLogic,WebSphere]
iii)Not portable[dependent on server]

Employee e1=new Employee(101,"John",89000);


Employee e2=new Employee(102,"Robert",89000);
ejb.save(e1); --->table will be autogenerated/connect to the db/insert
query(datastored)
ejb.save(e2);--->connect to the db/insert query(datastored)

Employee e=ejb.load(101);--->db connect,select query


_______________________________________________________
we want

Simple as JDBC
Automated persistence like Serialization,EJB
Pluggable like XML
-------------------------->ORM
ORM - Object Relational Mapping
-------------------------------
refers to automated object persistence
of Java object into relational db
based on metadata that describes the mapping between
Java object & relational table

maps object to the relational db

metadata we provide using xml/annotation

advantages
1)Better System Architecture
2)Reduces Coding Time
3)Caching & Transaction mgt is inbuilt

ORM implementations
Hibernate,TopLink,EJB Entity Bean,IBatis/MyBatis
____________________________________________________

POJO stands for Plain OLd Java Object


POJO is a Java class which is not dependent on any JAR,Server,API

1)Employee(POJO)---->empId,empName,empSal(POJO Properties)
emp--->eid,ename,esal

2)metadata xml/anno

3)//client code
Employee emp=new Employee(101,"Robert",89876);
session.save(emp);---->
db table created,insert query auto generated,data will be fetched frm the object &
saved into the table

Hibernate
-----------
-Hibernate is a ORM framework which maps java object to relational db based
on the metadata we provide using xml/annotation

-open source
[go to the website--->download jar files free of cost]
http://www.hibernate.org

-developed by Gavin King

-non-invasive framework-POJO based[Plain Old Java Object]


POJO is a class which is not dependent any API,Architecture,Server.It is unit
testable & pluggable

-Hibernate can be used with any type of application


eg:-console,GUI,servlet,jsp,spring,struts

-Hibernate is purely used for persistence


_________________________________________________________

Factory Design Pattern


-----------------------
class A{
//BL
public void mymethod(){S.O.P("Hello");}
}

Factory class:-used to provide objects of class A


class B{
public static Object getObject(){return new A();}
}

class Client{
public static void main(String[] args){
//client code
A ob1=B.getObject();
A ob2=B.getObject();
A ob3=B.getObject();
}
}
________________________________________________________

Hibernate is
------------
ORM Framework
maps java object to relational db
open source
invented by Gavin King
POJO based
purely used for persistence
can be integrated with any type of application

Hibernate Architecture(various objects)


-----------------------
Configuration
--------------
entry point
holds metadata
used to build a SessionFactory

SessionFactory
--------------
heavy weight ,immutable
responsible to provide session objects
typically there is one sessionfactory per db

Session
--------
-light weight
-represents conversation between java application & db
-wraps db connection object
-one appln can open multiple sessions with db
-every session must be associated with transaction
-used to invoke hibernate CRUD[create/read/update/delete] methods
eg:-save/load/update/delete

Transaction
-----------
allows the application to define units of work-txn
beginTransaction,commit,rollback

_________________________________________________________
Employee e=new Employee(101,"Robert",89000); //transient object(memory)

Transaction txn=session.beginTransaction();
session.save(e); //persistent object(db)
txn.commit();

Transaction txn=session.beginTransaction();
session.save(e1);
session.save(e2);
session.save(e3);
txn.commit();
session.save(e4);
session.save(e5);
txn.commit();

_________________________________________________________
Flow
1)Configuration
2)SessionFactory
3)Session
4)Transaction
5)save/load/update/delete
_________________________________________________________
DTD-Document Type defination
It holds structural details of xml file

steps to develop Hibernate Application


---------------------------------------
1)open Eclipse--->select workspace --->select Java perspective----> create a Java
Project

2)Add hibernate jar files


[go to the website http://www.hibernate.org
download jar files]
[Rt click Project-->Build path-->configure build path-->
Libraries-->Add external jars-->select jar files-->OK]

3)create the POJO class[com.hibernate.model package]


POJO properties,ctors,getter-setter,toString

4)Do the mapping in xml files[keep in src folder]


[metadata-XML/Annotation]
i)hibernate.cfg.xml [Hibernate Configuration file]
DB driver,url,user,pass
connection pool size,show_sql,dialect
name of the class table mapping file

ii)**.hbm.xml [hbm-Hibernate mapping file]


[Class-Table Mapping file] here we give table structure
table,class,mapping metadata between object & db cols

5)
client code [com.hibernate.client package]
-create Configuration object holding xml inf
-using Configuration object create a SessionFactory
-using SessionFactory obtain Session object
-begin transaction
-create POJO object
-using Session object invoke hibernate API methods [save/load/update/delete]
-commit the transaction

<class> tag is used to map POJO class DB Table


<id> tag is used to map POJO identity with primary key
<property>tag is used to map POJO properties with db columns

Hibernate CRUD methods---->save/load/update/delete

**To retrieve record


i)load method but it throws Exception if record not found
ii)use get method[returns null if record not found]
------------------------------------------------------------------

Lab)
Store Product information
code,name,price,brand,manufacturingDate
write 4 clients
client1--->save 4 records
client2---> get product data based on code
client3--->update (give discount on product) accept code & disc in %
client4--->delete based on code

**create a package com.hibernate.util --->HibernateUtil---> static method


public static SessionFactory obtainSessionFactory(){
.....
return factory;
}
In All clients
SessionFactory factory=HibernateUtil.obtainSessionFactory();
_________________________________________________________

**Accessing multiple databases using hibernate


-----------------------------------------------
By default name of hibernate configuration file is
hibernate.cfg.xml
we can change it
multiple db
-------------
here we will create 2 configuration files
oracle.cfg.xml
mysql.cfg.xml

//client code
Configuration config1=new Configuration().configure("oracle.cfg.xml");
SessionFactory factory1=config1.buildSessionFactory();
____________________________________________________

Configuration config2=new Configuration().configure("mysql.cfg.xml");


SessionFactory factory2=config2.buildSessionFactory();
____________________________________________________
Session session1=factory1.getCurrentSession();
session1.save(emp);
Session session2=factory2.getCurrentSession();
session2.save(emp);
_______________________________________________________
**********challenge assignment(optional)
save book record in 2 different databases eg:-oracle & mysql
_______________________________________________________

**Generator classes
------------------
generator class is used to autogenerate the values for POJO identity/PK
1)assigned -programmer will supply the value
eg:-<generator class="assigned"/>
when we do not provide the gc its by default assigned

Here hibernate will auto generate the value not programmer


2)increment -auto generate start from 1 increment by 1
eg:-<generator class="increment"/>

3)sequence-auto start with x & increment by y


eg:-
<generator class="sequence">
<param name="sequence">mysequnc</param>
<param name="parameters">START WITH 1000 INCREMENT BY 2</param>
</generator>

4)identity-unique integer values

5)uuid.hex-unique hexadecimal values

6)uuid.string-unique string values

7)native-let hibernate decide how to generate the values


eg:identity/increment/sequence

8)hilo-auto unique values but always new value wud be greater than old value
min-low=1200
table-name="mytabl"
1222 1250 1263 1289

9)seqhilo-auto values just like hilo + sequence


1222 1224 1226.....
-----------------------------------------------------------

Lab)
Book-->bookCode,title,author,price,publicationDate
**use generator class increment/sequence to auto generate bookCode
**create console-based clients
client1--->save 4 records(no userinput)
client2--->accept code & print book information

***Create HibernateUtil class to obtain SessionFactory

---------------------------------------------------------

2 ways to provide metadata


A)XML Approach [Hibernate version 3]
-POJO/Entity class
-Client code
-hibernate.cfg.xml [db configurations]
-pojo.hbm.xml [class-table mapping inf/table structure]
B)Annotation Approach [Hibernate version4 onwards]
-POJO/Entity class with annotations[replace hbm file]
-Client code
-hibernate.cfg.xml [db configurations]
_________________________________________________________

****Annotations
-starts with @symbol

-used to associate metadata about some programming element like


class,method,variable,interface
eg:-@Override

-used to hold metadata along with the java code & so must be used for fixed stuff

-Annotations are inside the java code [not external like xml] & so if changed java
code needs to rebuild

**use
DB COnfigurations will keep on changing -[hibernate.cfg.xml]
Table structure remain same-[use annotation]

_________________________________________________________
Basic Annotations
@Entity--->marks a class as a Entity/POJO class
@Table-->specific table name
@Id--->specific PK column
@Column--->specify non PK columns

___________________________________________________
steps for Hibernate-Annotation Application
1)open eclipse
2)create java project & add hibernate+db jar files

3)create pojo class[com.hibernate.model] with annotations


@Entity,@Table,@Id,@Column

4)mapping in hibernate.cfg.xml last line


<mapping class="pojo class name" />

5)create client class[com.hibernate.client]


_________________________________________________________

Lab1)Hibernate with Annotations


create Customer class-->
custId,custName,contactNo,birthDate

create a console-based clients & use Scanner to accept input


client1--->save 3 records
client2---> load data based on custId
client3--->update contactno
client4--->delete a record
**use Utility class to obtain SessionFactory

_________________________________________________________

How to map has a kind of class relationship (Containment)


-------------------------------------------------------
Ex:-
Book-->code,title,price,
MyDate publDate,
Address publAddress
MyDate-->day,month,year
Address-->city,state,country,pin

****Component Mapping
---------------------
How to map has a kind of Class relationship[Containment]
when a class member is an object of some class.

@Entity @Table
class Employee{
@Id,@Column
empid

@Column
empname,empsal,jdate;

@Embedded
Address resAddress;
}
@Embeddable
class Address{
@Column
street,city,country,pincode;
}
//Here do not create a seperate table for class Address

-Here we use 2 annotations


@Embedded specifies not to create a new table for that property

@Embeddable applied to some class which wud be embedded in other class

_________________________________________________________
Create Hibernate Application with Annotations
1)Create Java Project -->Add hibernate jar files
2)POJO Class with Annotations(@Entity,@Table,@Id,@Column-Table structure)
3)hibernate.cfg.xml (DB Configurations)
4)Client Code

Annotations
@Entity -marks a class as a POJO Class
@Table
@Id
@Column
@Embedded
@Embeddable
Lab1-
Save Product Information(code,name,price) in the db
write 2 clients
Client1--->save data
Client2--->get data

Lab2-
Save Customer Information in the db
class Customer{
int custId;
String custName;
Address resAddr;
}
class Address{
String street,city,state,country;
long pinCode;
}
write 2 clients
Client1--->save data
Client2--->get data

Lab3:-
Save Profile Information of a Person
class Profile{
int profileId;
Date creationDate;
PersonalDetails perInfo;
EducationDetails eduInfo;
}
class PersonalDetails{
String firstName,lastName,email;
Date birthDate;
Address resAddr;
}
class EducationDetails{
String qualification,result;
int yearPassing;
}
class Address{
String street,city,state,country;
long pinCode;
}
Client1-->save 5 records(do not use Scanner)
Client2 -->Swing Frame to load data

______________________________________________________________________________

public class Car extends Vehicle{


@Embedded
Engine eng; //has a kind of class relationship
}

How to map is a kind of class relationship(Inheritance)

Hibernate Inheritance Mapping


-----------------------------
-Inheritance is the property by the virtue of which one object acquires
features of other object.

Eg:-
//super class
class Player{playerId,playerName,country,numMatches}

//sub class1
class Batsman extends Player{numRuns}

//sub class2
class Bowler extends Player{numWickets}

-To implement inheritance mapping in hibernate there are 3 ways


1)Table per Hierarchy
2)Table per concrete class
3)Table per subclass

In each strategy,table structure will change

1)Table per Hierarchy


----------------------
-Entire class hierarchy is mapped to a single table

-An extra column [known as discriminator column] is added to the table


to identify the type of record

-It will hold discriminator value which is different for each subclass

-Annotations used
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)

@DiscriminatorColumn(name="empType", discriminatorType=DiscriminatorType.STRING,
length = 20)
@DiscriminatorValue( value = "temp")
Here
Total no of columns=summation of columns of super & subclasses + 1 extra column
[discriminator column]

_____________________________________________________________
Lab)
Address
-------
String street,city,country,zip
Player
-------
int playerId
String playerName
int numMatches
Address resAddr
2 subclasses
Batsman
-------
numRuns

Bowler
-------
numWickets
write 2 clients
client1--->save 2 batsman & 2 bowler objects
client2--->accept playerId & print player details
**use Utility class to obtain sessionfactory
________________________________________________________

Inheritance Mapping continued

1)Table per class hierarchy we already learnt


Limitation:-
we cannot apply not null constraints on the table
___________________________________________________________________________________
_______

2)Table per concrete class


----------------------------
-A seperate table is created for each class
-subclass table has super class columns +its own columns

Limitation:-
super class columns repeat in the sub class table
hence duplicate columns
-Annotations used
@MappedSuperClass instead of @Entity for the superclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@AttributeOverrides
This annotation allows the super class column names to be changed in subclass table
___________________________________________________________________________________
_______

3)Table per subclass


-----------------------
-There is a seperate super class table having supr class columns
-subclass tables are related with the super class table using foreign key[specified
by
@PrimaryKeyJoinColumn applied in the subclass]
-Annotations used
@Inheritance(strategy=InheritanceType.JOINED)
@PrimaryKeyJoinColumn
___________________________________________________________________________________
_______

Lab1)solve player assignment using strategy2 for practice(optional)

Lab2)table per subclass using strategy3(table per subclass)


Address
-------
String street,city,state,country,zip

Student
-------
int rollno
String studentName
Date admissionDate
Address perAddr
2 subclasses
PrimaryStudent
--------------
String grade

SecondaryStudent
--------------
float percentage

client1---->save 2 objects (ps & ss)


client2--->accept rollno & print student details

________________________________________________

SQL-Structured Query Language


it is a language used to access any db
it works on tables & columns
eg:-select * from emp;

HQL-Hibernate Query Language


it is a language used to access POJO's
it works on POJO & properties
eg:-from Employee e;//alias
from Employee e where e.empSal>5000;
_______________________________________________________

various ways to retrive data


----------------------------
1)using get/load method we can retrieve only single record
-----------------------------------------------------
Employee emp=session.get(Employee.class,POJO identity);

what if we want to retrieve bulk data[more than one records]


eg:-all emps whose salary > 5000
all emps who belong to 'Sales' department
solution:-HQL [Hibernate Query Language]

2)HQL we can retrieve bulk data/multiple records


-----------------------------------------------
Query q=session.createQuery("from Employee e");
List<Employee> lst=q.list();
//HQL-->SQL-->fire on db--->return multiple records in a list

Iterator<Employee> itr=lst.iterator();
while(itr.hasNext()){
Employee emp=itr.next();
System.out.print(emp);
}

_______________________________________________________
HQL[Hibernate Query Language]
------------------------------
HQL is Hibernate's own query language

also known as object oriented form of SQL queries

it works on POJO & properties

we can easily translate SQL into HQL by replacing


Table name---->POJO class name
db column name--->POJO property/variable names

At runtime hibernate will convert HQL---->SQL according to the db


______________________________________________________

dbside
emp--->eid,ename,esal
javaside
Employee--->empId,empName,empSal
SQL----> select * from emp;
HQL----> from Employee e; here e is a alias

SQL----> select * from emp where esal>5000;


HQL----> from Employee e where e.empSal>5000;

SQL--->select * from emp where esal between 5000 and 50000


HQL--->from Employee e where w.empSal between 5000 and 50000

SQL-->select * from emp order by esal desc


HQL-->from Employee e order by e.empSal desc
__________________________________________________________

1)select * from emp ---->from clause


2)select name from emp ---->select clause

Using HQL we can divide select operations in 2 types


1)Reading Complete Entity/All columns(*) using from clause
--------------------------------------------------------
In From clause ,the entire row is wrapped into an Employee object which is then
added to the List.
Here each List element is an Employee object.
eg:-

SQL- select * from emp


HQL- from Employee e [here e is a alias]

SQL- select * from emp where sal>5000


HQL- from Employee e where e.salary >5000

Query q=session.createQuery(�from Employee e�);


List<Employee> lst=q.list();
Iterator<Employee> itr=lst.iterator();
while(itr.hasNext()){
Employee emp=itr.next();
System.out.print(emp);
}
__________________________________________________________

2)Reading Partial Entity/specific columns using select clause


----------------------------------------------------------
In Select clause ,the individual column is wrapped into an object which is then
added to the List.
Here each List element is an array of objects[Object[]]
dbside
emp--->eid,ename,esal
javaside
Employee--->empId,empName,empSal
eg:-
SQL- select eid,ename from emp
HQL- select e.empId,e.empName from Employee e

SQL- select eid,esal from emp where esal>5000


HQL- select e.empId,e.empSal from Employee e where e.empSal>5000

SQL- select count(*),min(esal),max(esal) from emp


HQL- select count(*),min(e.empSal),max(e.empSal) from Employee e

------------------------------------------------------------
Query q=session.createQuery(�select e.id,e.salary from Employee e�);
List lst=q.list();
Iterator itr=lst.iterator();
while(itr.hasNext()){
Object[] obj=(Object[])itr.next();
System.out.print(�Id=�+obj[0]);
System.out.print(�Salary=�+obj[1]);
}

__________________________________________________________

//runtime Parameter binding using positional parameters start from zero


Query q=session.createQuery("from Book b where b.price between ? and ?");
q.setParameter(0, min);
q.setParameter(1, max);

//runtime Parameter binding using named parameters using colon :


Query q=session.createQuery("from Book b where b.price between :p1 and :p2");
q.setParameter("p1", min);
q.setParameter("p2", max);
________________________________________________________

Lab)
Gift(POJO)---->giftId,giftName,category,price
category eg:-Electronics,Toys,Accessories,HealthCare,etc

client-1)save 10 records

***using from clause


client-2)print all gifts
client-3)all gifts belonging to some category
[input category]
[use positional parameter]
client-4)print gifts in a particular range
[input minAmt & maxAmt]
[use named parameter]

**using select clause


client-5)print all giftname & price
client-6)print cheapest & most expensive price & total no of gifts
client-7)print giftname & price in a particular range
[input minAmt & maxAmt]
[use positional parameter]
client-8)create a swing frame having
2textboxes-min & max price
1button-show
JTable
on click of show button display gift inf in a JTable in that price range

client-9)create a swing frame having


dropdown holding category names fetched frm db
1button-show
JTable
on click of show button display gift inf in a JTable belonging to that category
selected frm dropdown
_________________________________________________________

You might also like