Hibernate
Hibernate
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
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
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
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
----------------------------------------------------
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)
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
}
public class Address implements Serializable{
String street,city,state,country;
}
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
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]
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
advantages
1)Better System Architecture
2)Reduces Coding Time
3)Caching & Transaction mgt is inbuilt
ORM implementations
Hibernate,TopLink,EJB Entity Bean,IBatis/MyBatis
____________________________________________________
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
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
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
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
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
//client code
Configuration config1=new Configuration().configure("oracle.cfg.xml");
SessionFactory factory1=config1.buildSessionFactory();
____________________________________________________
**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
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
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
---------------------------------------------------------
****Annotations
-starts with @symbol
-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
_________________________________________________________
****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
_________________________________________________________
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
______________________________________________________________________________
Eg:-
//super class
class Player{playerId,playerName,country,numMatches}
//sub class1
class Batsman extends Player{numRuns}
//sub class2
class Bowler extends Player{numWickets}
-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
________________________________________________________
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
___________________________________________________________________________________
_______
Student
-------
int rollno
String studentName
Date admissionDate
Address perAddr
2 subclasses
PrimaryStudent
--------------
String grade
SecondaryStudent
--------------
float percentage
________________________________________________
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
dbside
emp--->eid,ename,esal
javaside
Employee--->empId,empName,empSal
SQL----> select * from emp;
HQL----> from Employee e; here e is a alias
------------------------------------------------------------
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]);
}
__________________________________________________________
Lab)
Gift(POJO)---->giftId,giftName,category,price
category eg:-Electronics,Toys,Accessories,HealthCare,etc
client-1)save 10 records