Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Advance-Java-Hibernate-1

Hibernate is an open-source ORM framework that reduces boilerplate code in Java applications by managing database interactions. It simplifies CRUD operations and provides features like caching and exception handling. The document outlines the fundamentals of setting up Hibernate, including project configuration, entity management, and the use of annotations for defining entity classes.

Uploaded by

kp.at.workplace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Advance-Java-Hibernate-1

Hibernate is an open-source ORM framework that reduces boilerplate code in Java applications by managing database interactions. It simplifies CRUD operations and provides features like caching and exception handling. The document outlines the fundamentals of setting up Hibernate, including project configuration, entity management, and the use of annotations for defining entity classes.

Uploaded by

kp.at.workplace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Hibernate

learn Hibernate with TPA.


What is Hibernate ?
Hiber nate s|3 fromenork

HShernate was build alter naive of


It was build

Tn TDBC, we wsed to wte


Jot of coae.
nihen it Cones to hibernate, t triesto
reduce all the boiler plate code.

What is boiler-plate code cection of code


Boiler-plate code Tefers to
that hare to be încludedin many place
wh tle alteratioo change
Serve s klnd of templale olstanda
structu
partsf
hat needs be rpeatd
yarios of code
We call Hibernae an ORM framewnk
ORM standi for Ohiject Relationa Mapping
Th HPbernate, baie CRUD aperalions will be
performed in Pom of obiect.
#Why Hibernate ?
Open Soutce
Open Soutce. refers to a type of sofhuak
lcense4 alorelapment madel 4aat aos
Hae code softwane
to be hreely availabte f acessible publ
'DATE'

meanS 4hat any Can use, vlew,


madiy and dittrbute Source Codie.
Tu com cept is
Rcallabaralin,
daiseo direlop menk.transpoiancy commualy
Azpi"
(Troce similar in Tavo
)Aber nale hlps fo Mapping
Dalatypes of datahae
) Datatypes of Java
Table

) Hibernake helg to erite simgiedcode :


In Htbernade we haveot of obuilt
interfa ces, classes,methods, which oue going to
helo CRVD perations. we need to
wite any cade caplicitly For cxeatin connetion,
e Caeating" stakement, load daiver and 'so on.
HPbernate have nbailt mechanicm to perkonm
operatiom Hhat we need to
te take
Care of, whenerer we're performing cRUD
operakions in databae for Iaa
progom.
4)>Perfogsmance
Tn hibernate, we have mechaniem of
T-Level cache
I-Level coche

Cached
mohich
memoxy
red will be haldng Some data
perabita
'DATE

s) Exception Handlingi
Hibernade framenaoxk tself handles aall
checked exceptims but untime exeptiens
willhe thown
6)HQL Hibernate
There imight not
ury Longua
not beinbuttmethods for
all kind operakicns,using H I can
perfotm ny kihd of speratiths.
wibeQur Can
Jsing HQL
Hibernate..
Queries ce not speabic fo
Thele
datstabase,wken it Comes to Ho
any
queniei OUre database adependant
queries.
JPQL - Tava Persistance banguaqe
older nersiom wlhanede
Dewer versiox.

Howdoes Hibernate
Hibernate ioteracts ith databaie?

Suppore, have java applicahion


Jaya 4 it needs to interack with
dakabaie
Earlier, we understood ava
Tavainteracts with ID8C TDRC Datane
interacts with dier saftware.
dairer-software interacts
withdatabae Dri ver
Juva TDBL sof buare
'DRTE

In context ith Hbernte


Java ’ Hbernate < Data
baare

This time around e wiuwnite Java code


which interacts with hibernate thenhibernak
intcracts with databaye.
H
H ’ DB
In Jp8C e understood Hhat JDBC
Hae omlu API
which Can help estabish
Cammucation betwen Tava application 4
databae. ow we arere clealing ith hibernate
which s built upcn TDRCID OHibernate
internaliy
Hibernate
Jara Diver
Applicatom JDBO
Sortware DB

Eundameotals to Creoate Hibern ate maven


Hibernate Maven Project

Persistance. xml
ul Hibernate
user Databawe
password
We have to t wrie Java
Hibernate program
Hibernate is not present
pre Jent in TDK
4o add we n
hibernate
In pom., Xm], we dapendany te Tava
Tara prot
wil ad dapendances
Dhibecnak.
repecdie databae drier
In Future, if wewp necd o interact with diferon
databasethen
database dzier
we we
change the especti
&o bae mulkiple
database oiers
Persistance.xml i Cconfiguroation file)
contain url, wer, password ot
database.
Hibecnafe will be fetching infoumaion.
databasefrom persistance xml

# Whre to keep persistance Xm|.


maven- project ’ src/main /resources /META -INF
persistance tml

Steps: ko create hibernate maven fostgresq


latab
)Open. elipse ’ Hibernate - hibernate wockspace Cfolder
) CRtrl+n Create maveO GI:Com.qsp(rere)
(Simple Pieok)ject AI- Project Name
) Go to Google ’ search mvn repository
) Search Wibenate- core most wage /O vawmatibility
2)
Starh jtbc poshresgl driver ’ latest vrsion/ mot
hibernate-relocation jdbe postgrenl diver
Acess Modifiets -
-IDaTEl

Open pom xm- add <dependancies > </dapendacies> tae


dependenu
add biber nate- coe relocaien
daiver dependeny melated to poatsrcnl drict
addinq percictance.xm Gle oto
hibernattsetup
>Project mavenotoject.
project > add persistange. xm|
persigBance.
maveD
usr ulpass
lpassword
werd ]resoucy
in >Sre/main
sith dìec,use, META -INF.

while cxtating Entiby clas.:


#Rules to fallo) makeclae Con entihty
you want to non-abshoct
dass taat class must be public
dlas.
public casi duperModel f
g
ned to
clatt mucthavt primany key
Sntib
9public lass SuperMode!

Entity class must be annotated aith Entit


The variable to which you want to make l a
primary key, befn that an'abe, we need to
adnotatig
Entity clast needs to hare a public.
paramekeised constuctor a
public alefault
COnstuctoT
(T{ aess modiGer of elass public,obviously
moifier of
access conshucto il be puhlic)
'DATE

public class Super Modd f


Super Model (f

n2d to be variable of Entihy


Rule I AU the

and setters. private, and chouldclai!mut


hae qette
Entitu
public las Suparttsdel
pivate int id

SuperModel O4

Rale I(NoT Mandatory)


I is recommehded for Entity dass to
implemnt Serializable Iotert&ce
Note : Nhenerer e are sing annotations
GTd
akea tnnk.persi stence.
them from
Id, we heed to import

do we have bo follow thee


rues
The ruleshibenedaline
are quioelines and
and camnecticm
imposed by hiberna and TPA (Tava Percistence.
APr) o ensue Hhat entihy cdas ses are well
forn l can be
prapay hanageby
hrameodk.
Plopp ing ’ )Unicdirectima!
) Bicdirectienal DATE

Rude I Reouen
Hibernate need to
instances of entity classes making clast
instantiate & manag
ures theO hibernatee
non- abstact ensues
public & in
Create stane ofcass

Rule I Reamin database mas


elatiena E have
must
Erery entity
priman key hat defines cach
Hhat niqay
Thikey isused Por efficient
e uptates. By canenfarting. a &ingle
retieval
primary key, hiberaake maage entties
IA also helps elatin
consisteok taan tw0
ship bebwen twa
tables.

> Table Relationship


0 Maping
Untieional: One table fetch details
Can

f that toble ¢4 datails


another table witlh the helo
of pimary key- foxeign key lh
QcceesS

iectinaJ:Both tables can fetch_data


Bidiectina
details of that table
another table with the help
'DATE!

Rle M Rea.Son
Hibernake neade to cneak instances of entit
classes haring a public zeropara meBerised
constructor alosihernate tomake.
enitiesA oithout need of specific details.
Rale I
In Tava, priYate fetd wiually acceised
are
& moclified uting gekker and setter methed
Hibernate. need toUintecactwith attribus
enitiec. and publie
sekter mettods oloor
allawr beroate qetter
to do
this

Rule
affectiely
I Res son
Tmplemeating the Serializable Interface
iodicatesc inst ance Can be
Seriallzed comverbec t o byte shréam, und
sent acnesS netuwok.
netwok

Java DB
Appl
Server Servr

Porerequisiku to perform CRUD operahiasi


CRtateM Create
Entiby
ibyManager kaceny obiet
an interfack presend
Tavax.
.persiskence package
Marker Inter race
There ane 00 absract mchods 'DATE

Then have to cmate obiedt for


Enkity Manaqer
EnttyManager iSan Loterfaepresent
Tavaxipersistenepackage
With help o f a y EntibyManager, e have
to create. Eaktty objéct f0 Enby transaction
tHow to Cneate

EntilyManngFackeny entityManagerFackny Persiatence


erakeinilanugueFckan"psun
psun persistence-unit-name

EnibyManager entityManagerkackony
ctibyManng
Eotiby Transaction
CadEnkhyMasager)
enityTran Sachion =
entitytlanaqer. get Transactiom);

#whati EntityManag factasy esent in


Eakig interface
package Tavaxepesictane
What eackly EntibyManagiactay does
Persistant unit
Oload
EME) D8 Confi
Connection
pesistance,Kml.
'DATE

du databale configuratioms Qre


preient
persislane. Xm)

Persistonce i
Persistonce isa heoer class present in
Javax. persistance.
- From tisctass. we wil be wsinq metha
cneateEnkihyManagertacboy (Shing persttaatuoit-ra
CrateEntibyManager
Tt is
Fackony 0
public stakic method wkich rehrn
entiby ManagerFocèarg
Laave multile
ave datahaethen you
E Create mulkiple
It Czoshucted entibyManagezhactiy
for specifc cataba
halps in establishi ng connect ion ith databse
Entibytaagee haco O of
qet sbiect
also Wked to înstontiak
entihyManaqer.
enkibgManager i lEME
EM-CRUD operaton
We
going ka create entityManaacr aiat
with ap
entitytanagerhcng
SntilyMamgpratany Persistance. createEntiby Maraqer
enfiyManagractn Fackeng'periciast ut.mae
5atihyMag
entayManager ntiMaragutackrg
Ceote EnhiSMana_er );
DATE

With hele
opecatins.
In entiby
entibyManagee, We Can perform CRUD
Like
persist ) entihyManager
merge
ger, we ave metheds
remoe c), find )
entibyransa cti¡n :
Intrface prsent in Tarax. persistance
an

package
with halp of entibytManager,we are going to
objeck for entiyTanzacten.
EMF

ET

EntibyTransaction enbtyManager.
entibyTrans action getTransachion();
EntibTransackion to club mltiple
operlkin
entity ransachion. begln C)j
insert record
-update recond ’Transaction
-clelete

ity Transactiom.commit )
Now call all stteme
transacons
'DATE'

persist ) :
void
persist (objeck Eaéiky
Make an instance managed persisent
ParameBes :
entiky - enkiby iaskane
Thsows :
Enkiby Exists Exception - Te the
erists. enihy aludy
TlegalArgumenk Excapian - If the
entiby
TransactionRequiredException - Ie hate i_na
transachËon when invokel
a container

<T) T find (class <T> entihylass,obiut poimy


Paraeters:
dlas
entihyClait- eatikcass
primarytey primay ey
The found entiby
entib intanca
eaiy cloes. not enists.
Thmo
IlegalArgumntExcaption
'DATE

C):

UeT> T merge (T entihy


Paraneters
enhhyentiby instance
Return
the managed instance that the state was

Throws
>zlegalArgumtnkExcaption
TransactionReguiredExcepbion

void remove

Parameteg:
entihy - enbly instance
Throwe:
TlagalArgumant Excepion
Transation Required Exeption
-iDATE

|HTbecnake
We
Mapping to build melationship

+What i relatfonship
Cannection betweentno more
han to
tabler.

Whiy do we ineed to build relabionsbip


Student
id hame (omtact
Alok 36936 925
2 Keval 47 14136
3
Shubham S825 8244|
Ratina
java webtechQuerall
CPK]
2

2 2 2 2

Suppoe, e studem bable ¢ rabing table..


have
which rabing beleng to wich sdent 2
that is H con Pusinn that we wi be
Jaaving, Without
thee building
nelakianship between
tableswe wontbe able to tell
that
Ta build relatienship, wat to
hernate going
is a relation ship Inheri tance 'DATE
has
relationship - ComposithmDO
Pexture of hibernale)
sMappingMapping is
a

beb
using Mapping
tuo
we

moe
an establish relationdip
thantwo tables.
In RDBMS,we to maintain elationship
betwcen tables
e(Primary iag ee
kable prima
wil be
other table )

$UniDiectionad Mapping i
student
id [PK] Attk Name
Keval 62134s2891
Cenkack rating-id
Alok 734 023124 1

Shubham 38765432 1O1 2

RabingCPK) Java Sq Webteeh Overa

2 2
3 2

student
Name CemtacE
2132|40S G
Keval
Alok 234 SG 78 90
3 Shubham 43214S6123
DATE

id [Pr Webtech Overall


Java
sbuderta
2
2 2 2 2
3

+Bi-Directional Mapping
id CekJ Name Contact ratinq i
Keva 2467809872
2
Alok |234S6 78)0
Shubham 2
376S3 10s244|

Tava SQL Welotech Overall Student


CPk]

2 1 2

We wil make of Compoaition &ty to


bilal relatinahip in Hiber nate. ie. HAS
relaionaip
has Books
has Animali
) Store has Item
has Emplayees.
Wsing Hiber nate, we an establish nidirectiona
bidiretional maping
DATE

We further dasificàtio: in rekationship


One-to - One, Ccar has aa Engine an d
CPerson hasi socia Mdiai qecounts,
One-toMany
Those so cial media accounts belongs
ne persoo).and
Many - to - One( items to one Ordec )and
Many-to- Many Mant
(Muttiple stdents has mutiple
subjecks )
OncToMang Mapeing
bank
id localion acount.j
CPK] hesdquarter
8BI Mumbai 1 1 ,33’ Can only store
2 HDFC Pune atomic value
Kotak
leanglore
account
accountNoJaccoint ba lance contact
holder
324042 3hubham 324- 123
2 20424 Valbhav S30- S31
6306 S Akash J23345

bank account
bank d accountg Add extra table ir
databaue

22
33
2
2 22
2 83
"DATE

t ManyTo One

pubic lous Revieos ukie cas Prdack


pivate int id; private int id:
private Shin heading privote Strin
prevate doub! cast;
ommant
private Shi ng
@ManyTo One pulsli e Prducte
private Product product;
pubie Review
1/ Geer f Setters

Commentproduct_id
CPK1
Heading
Good Go for it
2 Bad' Wate
3 Wongt Don't Buy

Name Cost

mobile Go00

DnatotMany Mantou
'DATE

Takeaat fin
OneToMan VS
ManlaOne
DOneToMany
The sde Can acce99
teble
asso cited side entijes
mone flexible for updates.
To One"
Tue Side daesn't Lhave dinect
Cess to m side
So, iE is less exible

Many To Many (Unidinectfomal


Corisitering example of college There.
Many studete in and
prodes many subjects
S Core 3ava
Sa Web tech
J2EE
One gtudentan have mang ubiects,
One subject ian be b mang students
opted dany
QEnkit
public class 8tudent public cass idiett
lprivate int idi prirate int id:
rivate Stoing name private Sing name)
prvate Stöng emaili prirate sting desc:
private long ncbile -number piate Stáng trainer;.
QManytoMany I/Non-paramertsed
private Lt
7Non- prameet censuchr
/Non- parameterised conniudo 1/Getters f Setter
) Getters 4 Settes.
DATE

Student
namQ é-mai
lmobile-no.
Akoush AkQgng 82432)6S
2. yOacom 1234561
Yash Yacom
kalo:com 8|080 108
Kajo!

Subject
deserip tion trainer
Datetase
22 J2EE Middewr
33 webtech Fromtènd
Core-TavaGastcs Sk

student_subject
Stulid Sulb-id
(Relaionship)

1 22
2 22

From Student,we can fetch subiect but


Subiectwe can't fekcb student.
Taat's we call iE unidirectoral
accounts.adld ( account);
bank. setAccounts(accounts);, updates List
eT beginO update
eM merac.(bank ); >yp dates,accounts rel Nship
table
oank uith
empersist (account updates
eT. comnit C) ACCOunt to bane account
DATE

0Student SubËect
Studentanhroller Subiect Contraller
plethads ) createStudent c CreakeSubËeckC)
i)
2) fetch
i)d )fetcA)
HRL}TeRL
Aind suaject a) update
Addne 4) feteh() 4)eMove
1)id Andl) ii) fetchAU
n
a Shuzants) Update r ) Subjec
Add subiect ) ist <Subject>
jnto ist
Student student
Sudet
S)
Subjeck add
stulent
sert stdtert f
Fnset bect
Insert Data
Ginoid
2. Pind Date
Update Paty Subjec to
H, Remoe Data eistina student
Suitch Cc
s witch ( )

Case ádent details


do
sbject
Subjechsadd;
LAdd mee Tru
pome Fale)
ahile (
Studint. sek Subjects (subjeet
'DATE

Diflerence Between Uni-directiona and


Bi-dine ctiona!
AspectH Uni- dieotional Mapeping Bidirechonal Mapping
neinii One way Association. Associton
Ony on entity has Two way Assocation
hekcence to afher entity both t e ntities have
es to
references each other
Navigahon Not available Axailable
equire additimal quaeselaionship
directty thogh
frum lass Caur § dass Eugine
Target to )Souce
rdass Engine
-I/ Target Targetr
Source Car
Éngini engines Engine engine,
Campleris Sfmpler, fewer mappin Slighly
more complex
cComplex ,
considaration reqies additiol
cmsideration forr
mapping
Reatms Manaqed through foreign Managed thorough eferenes
Maintaince na the gO re botth sides
sides

Bi-di rection al
One ToOne
(@OneTo One
apping
CP) chasis
cost Mode' engineid ce Cario
350 2

2
CA4042000 2
Cwe3|3oooo THAR 3 3
DATE

Entit a¬ntihy
clas Car dass Engine
eiate int id: pivae int id
private hring model frvate
pringak
private OnToOne
OneToOne
privgte Eugine enginai Car car:
Ouetooe i bidirctanad
bidirrcttonal naapping eliminatizg
duplicake forcian-hog column
@Enti by
Car elais Eaginf
int id pxiate int id;
pzivate ti modul;
privae Engine
1Car
eginej private Cur car j

gttes setes
Car-jd Model e eid
CA

As we Lave seon previously


benoming key oother table ad
nnerse both bhe tables
'DATE

We ned not have foreignkey column in hoth


AaHes. e need to etash in any
table

public dass Cur


pablie cat Engine
pimte int id; pivate int id
prixate hing modal privale double ce
private Sing chasis;
private dou costi
OneTo One
( Toin Colu mn
Lprivate Engine enginei private Car car
Nou-para melernised coTshrucer INon -paramatuised cona
LGetterf Selters

TH is responsibe to czeae tregn


toreign keyalama
key
Car able

By 4hese lines, are


Qvoiding Creakon of
odga key in engine lable
diminate tuo fortÁign keys alu mn in Dabaloc
) add hibenake-coe
pom xml.
4 postaregl dependneies
nto
add persistence xml Ale in lder
META -TINE folcer

Comjsp. oto mool


class Car
fngine

You might also like