0% found this document useful (0 votes)
2 views

Advance-Java-Hibernate-2

The document outlines the mapping of entities in a Hibernate application, detailing relationships such as OneToMany, ManyToOne, and ManyToMany. It includes annotations for defining foreign keys, cascading operations, and the configuration of persistence units in a persistence.xml file. Additionally, it describes the implementation of an Employee Management System, highlighting key features and relationships between employees, departments, and projects.

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)
2 views

Advance-Java-Hibernate-2

The document outlines the mapping of entities in a Hibernate application, detailing relationships such as OneToMany, ManyToOne, and ManyToMany. It includes annotations for defining foreign keys, cascading operations, and the configuration of persistence units in a persistence.xml file. Additionally, it describes the implementation of an Employee Management System, highlighting key features and relationships between employees, departments, and projects.

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/ 16

DATE

v)To map engine in Car entity wte QOnaTo On


To Create in Car Enlity
wie Join Column foeignkyBver columo
engine enity
mélerenaeolumn
()Toin annotain ha (name =
attibute wich add foreign -key calua
mith particlar

table cHeaHng Foreign key in is

@JoinColunn ànnotati on remove


ferreign-key
We ae
column.
Speciy mapped n otther
eniy t we Rpreicnt
foanehnkey colum,
aibtk in wich we
have veriable name
o oin Calumn
OnTo Mainy and ManyToOne Ridiekina)
mapping
OneToMan 4 MayTaOue bidiechiona)
nelationsaip
Can be
mean that the allociakion
in looth. dinectiorOs.
Cooments associaed with post
) Customer Can hare mutiplk
DATE

9Entihy
public class Bank publie class Account
QId (a Id
private int id; private int id
private Shing na private Sting acc-hn;
picate Sbing locahion; poiate olouhe balanca
'@OATaMany OManyToOne
pxivate ist<AcCount acCounts i private kaunk bank:
INon-parameterised constuctor /Nm-parameterineol conste.
Getters f settrrs Getters &Sekters

bamk To
>Acc nam locatio acch-nanJocaion
Bank.set C

persist
MemareBe
nove paricutaracOu
haeidccount i

when many entiy tgiug acce ss


enliiy
bade
be cones mangTh cne
9donein
acconl
relatinship ity's table
manentiby's
ácC-hname loc
hlame locaion atienhanki

accountjd
'DATE

Many ToMany Brdirectional (Students to Subi


Ettmlnate qth table. Subict
ManyTo Many Cannotti on)
This annotation establishes
relationship between Student f Subje many-ta-many
The: Many To Many mappedGy
mappedByicater tha student Cteld in
subject dass isthe wning side of the
srelationhip. Tt mean the sbËect elass
responsible for managing the associatio
tablet
@Toin Tablecannotatiom
Tspecifieeg te details of ascociaion
tahle that wsed tó store elationship.
betioeen Student 4 Subjeck
foin Calumns (attrbute)
It spe cifies Faneign key calumn in tue
Lasochoation
sfde
tuble. coesponding to Subjeck.
inverseJoin Coluons ( attibute)
Specifies the fereign key colimo
associakion table tresponding to stab
Shudent side.
I4- studenks-subjects-mtm diminte tat

How the mapping orks


QManyTaMany arkociatian creates aloin Table
ino the database to imanage relaticaship
between Subiect 4 Studen
The mappad Bu ahihute in QMangTa Many
Te ascociatimin the student clasg
indicates Hhat the students ield is the
Ownin side
>The O@ Toin Table annokaion io the subject
clas specifies te details oaccociakierg
Able including
Calumns
Vame
focignkey
Withtuis
tais confiquraig
con se cannavigoe
thehare elationship
skuden
bidireckianaly
objeck,you atn accele
ascociated. subiect and e verea The
nelationshp mankged Hhaough astociatian
kable and changes to eitatside of o
relatimship ill bereflected
the relationship. he
dakabase.
Pensitence. xm
Quu Hovo to get Persistence.xmlale
Search Ufor " Hiher nate oit, "persistencexml
le formaf afficia mehsite "
xml Ale helps to keep all confiqu
persictence xn
nationles.
Tn pecsistenceoxml fle under <eersiskence)
Can Lane multple plepersistence units
DATE

hane multiple persickence unit, Ho


Hibernake identihy pacticular Perickenct uni
unit need to hae
tvery persictenaeunit
unique name b taat unique nameibe
identifies particula! persictencd uait
Note & Tn an 0ppli cation, We Can have ly ome
persicdence Xn)Ale
Kperiktena -unit ne me>"ps-name" thansaction-dypez RsoR
<eropertie
<- DR priver
name="Ja vax.persistence.sdhc.doinen
value "fuliy qualifid namQ

nama avax.persishenca. (dbe.url


yodue R local host is32/DR nam
<!- DB User
<pnaperty name e'auax.persistente«dbe, user" ralue: "DB-wser

<potsperky name 2"'javaxparsistena


-
jdbc.passwod"value'bg.pus
< D8 Dialect
<poperby nanu "hibernate. dNect "
value ="ora. hibernate.dialet Postgres(qL Dialect>
<it- emeake cmeate -dop pdabe -->
Spraperty name 2Mhibernae hbm2dd l. auto" values'update
4-Sho) SOL fn console -->
narne "aibeenake.sho0- Sql valestue "/>
<prapety namé "hibernate. format sl" value aet
<psaperties)
</persskence.-unit
l'DATEI

Clas
Entit
@
Table ( name deied tolea namt)
L we don't want enHby caseName ay Table name
We can make ue f o table annotation alom
with name atbribue by ehich we can spetfy
differe nt talalengme cpart fon enity cdas
name
NOTE& A aphabet neads to be in lowercaie
Geneaaked Value Cshrateqy eCenetatim Iype
If we want primay key key ta be generated aute
poaticallye can ke wue cf Jyis onnctati
ithSuitableattribute detils
(aolmn Cname = desired coluimn name
To proxide specifie column name apart
Aom idenifier in Enty cdass, e moke
se (@ Column annoo!Hon with
attbue name,
49@ Cr ation Time Stamp
I wil aulomatically insert crnent date
and 4o0e
ime froon machine k localdate e time

hiberok. dialect ’bêry AppicaBion is not smact enaugh


to peek d Bicka
ick database, so we Use
dialeck R specify wlhich databaie we ae wiing
hibernalehbm2ddauko ’ hibernake mapping to
data definition
valees ) CREATE Ulagug
even taaugh table exist, erery time when
gxarn applcalion , all perious tablee u be
deleted & 1gcin new tables i be cnealed
DATE

valuei 2) UPDATE S
TE table exiks, Hacn t oont ereake. the tahle
table da nofexit,it wil creale table

Cascading
Itis behavious of aperations prapagatina
entihy to
allaar yoy tol Aeftne haw cerlain cperat
should affect siher eated
enti tiei

There ae differrot types


associated with CRUD
operattans, typicaly
operatfan.
los Cas cade. PERSIST
Ondy the persfst operation Rs cascaded to
assocated entities means when you persist
an entHty, the asac?afed eniLfe ane ase
persîstedg
Cascade. REMOVE
remoe operalion is
used when you want to delete an entit
assoctated enties.
Cascade.MERGE
Only merge apertion is Cacadel
he
Tuis ied ou want change
madeto detach entiby to be gynchnazed
with pergistence. Conbxt.
DATE

Cascde. A
AU operatimspersi
All
cascaded to
memone
associated
enti detacpesh
mergemeh

Bity ctos Anataktog


#What Genenaliam Type
table, we necd
wheneVer aNe caéating pimy
We
leey calumn
paima key column, Tuis NULL Generated
neads to wnique and NoT
provide solutfom by
k pot null pimay key
cxeating
Cutomaically
Column Annotakion Paoperies
lcolumn (nlble
Default value f nullablei briuc tHoat
Hhat means
We addnulalues. When wite
nullable = falee wecaDnot add null valne ta
Aat Held

By de failt ,it î false. that meansolpliabe


valo llowed hen.
unigu true cannot add dslicate
we
alues it should be unig ue.Throws Exceptier
Updatable
bhe thet Mee
ne cond, hen we wite Mpdatabea
apolatable =false., we cannot upoate that Held
'DATE

Uni pue=ta noTE :To pzavide a d column, multiple


nulablesfale
an
eparatel by
addiny mulkiple feature Seokura,
Hibernate I-level- Cache
Caching ingeneral
ingenera is a temporay meman
wil bectored
A8Sme
temporany
Ofonationoich uofU be
Arecuanu
toina the informaon n empsra
6ytoing
memothe Operfor manee ef applioaklom
bincaeasednmproved. Tor 4he sar
Same
have aching nechanism n
hibernote
Ideal cache is to reduce the
databae queris, hence ducing
throughput ime ct he apAlicakon
Htbernae comes with tuo deeereat
of cach)ng
I-Level- Cache
) n- level- Cache

NoTE : In hibernate I-level- Cache R enabled


aydefault
DATE

u cache
Sat

Java
Agp" entihyMaragr PatoBase

enikyManaqer2
kiaceshe entizManagthactag
+Abemake I-leel-Cache
I-lerel Caching in hibernate is not prorided
by default We le Oneed to add extra dependania
to enableI n -level-caching There
many thind-party vendot O oho rovide
depeldecies to dchiexe N-lerel- cache.
Example EH Cache, oS cache, Zsaiarm cache
Tboss cache
rt level ncheis one or each entityManager
d leve) cache e cne orr entihybManagerfaco
-level Cacheoiu be sed by entily
Mamagers. whoever Conmes under Ahat partiAulac
enlityhianage~atta
Le
RS,I be Cache
S
Tava
cntib anagerl
cadhe
I

entibyManagerfactory
-| DATE.

-Hoxw to cdd I-level- cache 9


On mnepositoy searchfor EH cache
Than we hqye to enable I lee)
persistence. xml cahe Hr
entily
Cachab
dac, we need to we annotaon

Htbernake Lfe-cyde
Tnansient State
Ohject is
existing but there is no laion
ther is no Connection, tetween that obie
etabe în the database
Persistence State i
In thesstateobject< row in the
table ConnectedI ou make any
changeS in Hoat dbject it may hamper
Hha daka pre sent in datahde or Table
NOTE Any soiect wich is
be caled by gasbage callectox
Consale- baied- hibermate Pzoject
’Tech Stack
Backend fava Hibernate (PA)
Dakabase
Build Tool i
postaxtsql
mahen

TITLE Emplayee - Management Syetem


Problem SbatementDesign implement emplayee
anagenent syitem uig Hibecnate l Databalet
Systenn shoul alow Oefficient
efficient manag
managemat t
émployee infor matioincluding detais about
-DATE

hir dapartments Cre


associated

Enti ties

2. Name
S. positin
3.Dateof Joining
nÒ Departtcen 2
Relation ships i
ManyToOne ; Employees HAS
" Depart ment
jEmploy ees HAS rojecks
ManyToMany
) Depat ment

2. Narne

Reloti onshipsi
OneTo Many 3 Department HAs Emplayeel
3) Poroject
Atibutesi . Tl
2Name
3. Deseriplion
Relationships
ManyTaMan pooiects HAS Emplayees
DATE

Key - Features &


1)
Add Employees E
Alow oadding ne
emplaees oith det
Specify the department prajats
with each employee.
2 View Employee Tnfoxmation:
Display mployee dtails
datails includin depazten'

3) Update Employee Details 2


Allase pdating employes infamalin sal
or position
4)Remove i Employee i
Proxide an Gption to
toemove
emlayte
from the aytem
s)New Department Information i
Display department details along with
emplayee
)Add Depart ment &
Al addirg depastonent
Z) Add
Allo udoing nen
pxoject.
(
)ew Project Iafoematon
Vie proieak aletails with ist o
employees fret hvoled
'DATE

Learning-Öppostunihes
Tnpmnting
-appina
Hibernate annotatand forr
Handling: alSociationy (MTO, OTM,MTM)in
Hibernae
Perfoeminq CRuD speratios. ing Hibernate
Underst qndna transaetion
hibernate.

Muic -App Munaq cment


>Tech sta ck
Rackein ava, HibernakeTeA

Build Tool :
PostqresQA
maven

THe : Music -Managtoent Systenm


Prroblem Staemanti
Deaign & implemant musiemanog emeat ayihem
usin Wibernate RDataloase Sytenm sholdallau
eEERent manogement Songs informakom
including abaut artits, playlists
a ssociated ith them also the wier having
playlists Fcmingfrm sngs

Song Attibutee
2) Lile
3) arbist-name
Relakfonships
O ManToOne
i
Song Has Artist
MaoMang Song HAS Plaglists
DATE

2) Plsis Artist :
Pributes
2) name
Relationshipsi 8)
1))
OneToMany 3 Artist Has Gangs
3) Playlist
Attributes
2)name
Relationships :
DManyTa0ne
2) Man
s PlaylÊsts Hai User
Ta Many Plalsts Has Sangi
4) User
Attributes? ) d
2)'ername
3) pass word
D
Relationhips 2
One ToMony i User Ha
Key- Featunes :
Playlite
1) Add User
Alloxe) adAing Wser
ith plalist conkaining
Songs nd artist infoion to

2)View Users playlistsi


Displau playtat
3)
chasen h user înocludingt
Add
Smgs and hein artist 3et to
DATEI

Remore Songe
Provide an aptin to d>leke
Aeletiag Aroon playlits
S) Update fstske playlists
rtming
Alow ugdating plaglits adding
c) Remoe Playlt
Ala an option to wSer for remavint
playletr with asocatedSOoN

Add Plaglist
Alloadding new) plact
View Scngs
Alow VAlsplaging song'e informatioxn
9) VewArtist
q artít nformaon
Empl
ic
oyyee Project Oepartment
eid
deptd Pr-id e i
23 23
x23 2

e-id Par-id Pride -i deptid

2 2
2

2 2 3
2 3

You might also like