8/9/2019 Hibernate (1) notes
1/691
Hibernate:
Hibernate is a frame work. Hibernate frame work is used to develop a
java application to interact with database server.
A frame work is a piece of software this piece of software contains
solutions from commonly repeatedly occurred problems occurs multiple
projects.
IDE (Integrate Development Environment):
As part of IDE all the components all interated.
Ex: Editors! "ompilers! #ervers! $rowser etc.
$y usin IDE we can develop project %uickly.
IDE is will improve the productivity of the developer.
&he followin are the most popular IDE!s.
1. Eclipse'. (y Eclipse). *et $eans+. ,AD -,elational Application Development/. 0 $uilder
&o work with IDE we re%uired a workspace2 folder.
A work space folder contains all the 3les which are related to that
project.
4hen we double click on Eclipse.e5e it will launch a dialo whose nameis work space launch. &o this work space launch we have to supply work
space folder as input.
4hen we start the Eclipse IDE in the work space folder it has created a
folder with the name metadata. &his folder contains all the 3les which
are used by Eclipse IDE.
Eclipse IDE contains set of perspective by default Eclipse IDE launch6s 0EE
perspective.
A perspective contains set of views. A view is a Email window. Aperspective contains set of views.
If we would like to perform any operations in IDE we must create a
project.
Procedure to create the project in IDE:
#tep 1: 3le new project.
8/9/2019 Hibernate (1) notes
2/691
#tep ': select the appropriate project and click on ne5t button.
#tep ): in new java project window enter the project name and click on
3nish.
#tep +: we delete the project with out checkin the check bo5. &he 3les
will not delete permanently.
As part of java prospective we use out line view to see all the variablesand methods which are available in class.
&he packae e5plorer view is used to see all the 3les which are available
in the project.
#elect 7roject 7roperties java $uild path library add
e5ternal jar 3les.
In IDE we can disable auto build process -7roject builds
automatically.Note:
4e can chane the short cuts of Eclipse IDE
-4indow 7references 8eneral 9eys.
As part of a Eclipse IDE we can replace or et the old code by usin
compare with or replace with local history.
&o create a jar 3les we use an option e5port -3les e5port.
Procedure to create web based application:#tep 1: 3le new web project.
#tep ': &he above step will display a dialo with the name ;new web
project6. In that dialo enter the project name make sure that project
name and web root folder name is same.
4hen we work with IDE to con3ure in deployment descriptor we have
two options. &hey are like source and desin. &o see the contents of
web.5ml 3le we can use an option source.
$y usin raphical user interface if we want con3ure servlets. 4e can
use desin view.
4hen we use IDE we no need to deploy the project manually. 4e can
con3ure IDE to deploy the project. As part of 0EE respective. we can use
server view to con3ure the project in IDE.
"trl
8/9/2019 Hibernate (1) notes
3/691
#tep 1: 8et the server view and riht click chooses an option con3ure
server connector.
#tep ': "hoose the appropriate server the home directory of the server.
#ame servers
re%uired user name and password supply these values and click
on =92.#tep ): &o add the project to server we can use an option add
deployment.
#tep +: &hey are some IDE6s are available which are responsible to
interact with database
#ervers. &he popular IDE6s for oracle database server are &=AD
and #>? developer.
@or the database server like (#>? we
can use (#>? workbench2.#tep /: In the companies because of licenses issues we may not use the
IDE like &=AD.
Eclipse ives has provided a feature to interact with database
servers. 4e can use
EclipseB(E"?I7#E to interact with database servers.
Procedures to confgure IDE to interact with database server:
1. =pen (E"?I7#E database e5plorer of prospective.'. In the database browser view when we riht click it lunches a popup
menu from that choose an option new.). &he above step as lunched a window whose name is database
driver from that choose driver template and provide a driver name.
*ow we have to supply driver class! url! username! password to
interact with D$ server.
Hibernate is a rame which is used to interact with database
server:&here are so many frameworks are available in the market there are
some of struts! sprins! 0#@ etc.
1. #truts! sprin frame works are used to develop webCbased
applications.'. Hibernate is a technoloy are a framework which is used to interact
with database server this framework resolves all the problems of
8/9/2019 Hibernate (1) notes
4/691
0D$". In a project if he tries to use hibernate frame work if he
develop the project %uickly.). As part of 0D$" we have to write lot of code to hardly checked
E5ception.+. As part of Hibernate we no need to provide the code to handle
checked E5ception./. If we use 0D$" a prorammer is responsible to reister the driver
and et the connection. 7rorammer must provide the code to close
the connection. As part of Hibernate he is responsible to open the
connection and close the connection.. As part of Hibernate it6s only starts the transaction and ends the
transaction. Hibernate internally uses 0&A -0ava &ransaction A7I. &o
start the transaction and end the transaction.. Hibernate support internal connection provides Hibernate uses ")$
connection pool. D$"7 connection pool. If we went to use e5ternaconnection pool like webCloical we can con3ure it. If we use 0D$"
we have to provide the code to handle database speci3c error code.F. If we use Hibernate we no need to provide the code to handle
database speci3c errors.G. Hibernate supports it6s own %uery lanuae H>? -Hibernate >uery
lanuae to resolve the problems of some java application to
interact with multiple D$ #ervers without chanin the %ueries.
1. In case of 0D$" we have to provide thecode to remove the hard codin. In case of Hibernate we provide
the details in Hibernate con3uration by readin the details from
con3uration 3le -.(?. It will interact with multiple Database
#erver.11. If we use 0D$" prorammer is responsible
to write the code to enerate the primary key values. As part of
Hibernate they have provided preCde3ned class to enerate primary
key values.
1'. $y usin Hibernate we can represent the%ueries in the form of object or we can use criteria A7I. As part of
Hibernate we can achieve polymorphism between the tables and we
can achieve association also.1). by usin 0D$" we can6t transfer result
set object from one proram to another proram -result set can6t be
transferable to resolve this problem we have to provide the code to
8/9/2019 Hibernate (1) notes
5/691
retrieve data from result set object and store it in array list object if
we use Hibernate. Hibernate does all these work.1+. we have the technoloy like E0$ to
interact with D$ #erver we can6t run E0$ Application without E0$
container. 4e can6t use E0$6s in all type of application we can
resolve all these problems we can use Hibernate.
&he followin is true Architecture of Hibernate framework.
Hibernate is called as =,( tool are =,( framework =,( -=bject
,elational (appin.
In the market they are so many =,( frame works are available some of
them ere Hibernate! 07A -java persistent A7I 0D= -java data object i
batches! #&= -service data oBp! &op ?ink etc.
All these frame works are used as =,( &ools. &he diJerences betweenthe &ools are the names of the classes are diJerent.
In the database server the data will be stored in the side the tables
between the tables we establish a relationship because of this reason we
call it is relational data.
Hibernate #B4
0AKA Application
0D$" A7I
D$ #erver
8/9/2019 Hibernate (1) notes
6/691
,epresentations relational records in the form of object we call it has
=,(:
7roduct
can we use 0D$" to represent records in the form of objectL
A. es! we can use 0D$" to represent the records in the form of object.
In case of 0D$" we have to provide hue amount of code torepresent hue amount of data in the form of object.
$. As a Hibernate developer we need to develop a java application
with uses Hibernate A7I and interact with database server. If we
want to develop a java application we need to con3ure D$ server
and provide some additional 3les to Hibernate software.". If the Hibernate software to communicate with database server we
re%uired a user with special privileed -se%uence the tables in the
database server must contain primary keys.
Procedure to create user and assign some privileges:
1. ?oin to database server usin administrative user use the
followin command assin the user and privilees.#>?M create user hib ide3ed br abcN8rant connect! resource to hibN8rant create se%uence to hibN
'. 4e have to create the table with primary key.#>?M create table emp -eno number-+ primary key! ename
varchar'-'!Address varchar'-'N
#>?M create table product -pid number-/! name varchar'-'!
price number-1!'N#>?M alter table product add primary key-pidN
). 4e can et Hibernate software from Hibernate.or
1 7no 1
' pname'
) price
1
7one
1
'
7&wo
'
8/9/2019 Hibernate (1) notes
7/691
+. Hibernate software is a collection of jar 3les the most important jar
3le is Hibernate.jar/. If we want to use Hibernate software we have to develop the
followin ) 3les./.1. Hibernate con3uration 3le
/.'. 0ava $eans -7=0= classes -plain =ld 0ava =bject/.). Hibernate (appin 3les -hbm. Every framework uses con3ure 3le. &his is the startin point to
any framework enerally the con3uration 3les or 5ml 3les-we can
use property 3les also as con3uration 3les. in Hibernate we use Hibernate.cf.5ml as the con3uration 3le we
can chane the con3uration 3le name accordin to re%uirement.F. Hibernate con3ure 3le contains the entire information which is
re%uired to communicate with database server. &hey are:
a. Driver classb. urlc. usernamed. pwde. dialect
Hibernate.cf.5ml
G. Hibernate software re%uired the java proram to represent a record
in the form of object. $ecause of this reason we have to develop
couple of java prorams this is based on the number of tables
available in the database server.1. &hese prorams
contains instance variables! set,ow- and er,ow- methods.
Developin these prorams are easy because of this reason 7=0=
classes are known as -plain old java objects.
driverOclass Poracle.jdbc
url P jdbc.oraQ.
username P hib
password P abc
dialect P =racleDialect
BBinformation about H,( 3les
8/9/2019 Hibernate (1) notes
8/69
8/9/2019 Hibernate (1) notes
9/691
1. (ust contain a default constructor.'. (ust be placed inside a packae.). &he 7=0= class supports properties. A set,ow- and et,ow-
methods are called as properties.+. 4hen the Hibernate people are developin software they are
started usin the help of other software6s. &hey are like &ransactionA7I! "onnection &ool! Dom 7arse! cache jar 3les. If we would like to
run the Hibernate software are need to make sure that all these jar
3les enerate the "?A##7A&H other wise Hibernate software will fail
to run.
Hibernate #B4
QQQ.. Etc
7rocedure to con3ure the Hibernate software and enerate Hibernate
con3uration 3le by usin (yEclipse IDE.
I. #tart (yEclipse IDE pointin to works place folder.II. "on3ure (yEclipse IDE to interact with the D$ #erver.-create D$
$rowserIII. "reate a java project and add the packae to it.IK. Add Hibernate capabilities to the above project. (yEclipse
project capabilities Hibernate capabilities.
K. "hoose the re%uired jar 3les to be added. -"ore library and
notations.
Hibernate).jar
0&A.ja
r
")7.j
ar
Dom.j
ar"ache.jar
8/9/2019 Hibernate (1) notes
10/691
KI. "hoose new Hibernate con3uration option and click on ne5t
button. @rom the list of available D$ Driver select to which database
server we have to connect.KII. "hoose the packae name and provide the class name as =,A#@
and click on 3nish button.
Procedure to generate hbm fles and P"#" classes:
#tep 1: 8o to (yEclipse db e5plorer perspective and establish the
connection with Database server.
#tep ': #elect the all re%uired tables and riht click on it enerates T
launch popCup menu from that choose on option Hibernate reverse
Enineerin.
#tep ): #elect src and packae and check the 3rst ) check bo5es and
click on 3nish button launches abstract class.
#tep +: &he followin is the con3uration is Hibernate con3uration 3le.
UhibernateC"on3urationM
U#essionC@actoryM
Uproperty name P "onnection.driverOclass2M
oracle.jdbc.driver.=racleDriver
UBpropertyM
Uproperty name P "onnetion.url2M
jdbc:oracle:thin:Tlocalhost:1/'1:5eUBpropertyM
Uproperty name P "onnection.username2MhibUBpropertyM
Uproperty name P dialect2Mor.hibernate.dialect
=racleGiDialectUBpropertyM
Umappin resource P infoBinetsolvBproduct.hbm.5ml2BM
Umap resource P infoBinet#olvBEmp.hbm.5ml2BM
UB#essionC@actoryM
UBhibernateCcon3urationM BB #ave hibernate.cf.5ml
#tep /: &he followin is the 7=0= class of emp tables.
public class EmpR
8/9/2019 Hibernate (1) notes
11/691
private Inteer enoN
private #trin nameN
private Double salaryN
BB provide setters and etters methods
above instance variables.
S BB #ave Emp.java
#tep : &he followin on the tas of Employee 3le.
Uhibernate mappinM
Uclass name P info.inetsolv.Emp2 table P Emp2M
Uid name P eno2 type P java.lan.Inteer2M
Ucolumn.name P E*=2 presission P s2BM
Uenerator class P assined2BM
UBidMUproperty name P name2 type P java.lan.#trin2M
Ucolumn name P *A(E2BM
UBpropertyM
Uproperty name P salary2 type P java.lan.Double2M
Ucolumn name P #A?A,2BM
UBpropertyM
&he followin are the most important interfaces and classes.Interaces:
1. or.hibernate.#ession@actory'. or.hibernate.#ession). or.hibernate.&ransaction+. or.hibernate.>uery/. or.hibernate."riteria
$lasses:
1. or.hibernate.cf."on3uration
&he followin are the steps which will be used to develop Hibernate
application.
1 "reate "on3uration =bject.' "all the "on3uration- method by usin the "on3uration =bject.
8/9/2019 Hibernate (1) notes
12/691
) 8et #ession@actory =bject by usin "on3uration =bject! we use a
method build #ession@actory-.+ 8et #ession =bject by usin #ession@actory. "all the method
open#ession-./ 8et the &ransaction =bject.
"reate the 7=0= class =bject which we would like to perform the=perations. #tore the data in the 7=0= class =bject.F "all the methods saveBupdateBdeleteBload methods.G End &ransaction by usin commitBrollback.
1 "lose #ession =bject.
11 "lose #ession@actory =bject.
%e&uirement:
Develop a Hibernate application to insert records in to the emp table.&he followin is the java code which is used to store the data into emp
table.
public class #toreEmpDetailsR
public static void main-#trin arsVWR
"on3uration cf P new "on3uration-N
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N#ession hsession P sf.open#ession-N
&ransaction t5 P hsession.bein&ransaction-N
Emp e P new Emp-N
e.setEno-1N
e.set*ame-,aju2N
e.setAddress-Hyd2N
hsession.save-eN
t5.commit-Nhsession.close-N
sf.close-N
S
S
Note:
8/9/2019 Hibernate (1) notes
13/691
4hen we ,un the same application for two times we ot an
E5ception sayin that "onstraintKiolationE5ception.
1. 4hen we create the con3uration object we are create an
environment to store the con3uration details. In this con3uration
object we can store Driver class! url! username! password andmappin information.
'. 4hen we call cf.con3ure it checks for hibernate.cf.5ml 3le in the
"?A##7A&H. If it is available it start readin the contains from
hibernate con3uration 3le. *ow the hibernate 3le the
correspondin hbm 3les it opens all the hbm 3les and try to read
the contents from all hibernate mappin 3les. All this information
stored a 0K(6s memory -con3uration object. If the con3uration
object not available in the class objects it throw E5ceptionor.hibernate.hibernateE5ception.
Note:
&his method is an E5pensive operation. In a project it is
recommended to call the con3ure method only once in the project life
cycle.
public class #toreEmpDetailsR
public static void main-#trin arsVWR
"on3uration cf P new "on3uration-N
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N
#ession hsession P sf.open#ession-N
&ransaction t5 P hsession.bein&ransaction-N
Emp e P new Emp-N
7roduct p P new 7roduct-N
e.setEno-1N
e.set*ame-,aju2N
e.setAddress-Hyd2N
p.setId-1N
p.set*ame-,ice2N
p.setAmount-1N
hsession.save-eN
hsession.save-pN
t5.commit-N
8/9/2019 Hibernate (1) notes
14/691
hsession.close-N
sf.close-N
S
S
&his method is an e5pensive operation in a project it is recommended tocall the con3ure method only once in the project life cycle.
In any frame wrote we can chane the con3uration 3le name accordin
to our re%uirement.
If you are usin our own con3uration 3le name we have to use the over
loaded con3uration method.
Ex: cf.con3ure-myproject.5ml2N
Note:
&he default con3ure method always check for hibernate cf.5ml3le. It always recommends usin .cf in the con3uration 3le name.
$ecause of this we can easily reconiXe the con3uration 3le name.
hibernate.cf.5ml
.hbm.5ml
4hen we call cf.build #ession@actory- method it ets driver class! url!
username and password these values are supplied as input to hibernate
internal connection pool. *ow the hibernate internal connection pool. 8et
the connections from database servers.
con3uration-N
8/9/2019 Hibernate (1) notes
15/691
*ow the build #ession@actory method ets a connection from connection
pool and establish the connection with database server. It will check
weather all the re%uired tables are available or not. If not available if
re%uired build #ession@actory- method create the tables. It is the
responsibility of hibernate build #ession@actroy- to create all the ;"Y,D6
%ueries for every table and store the %ueries in 0K(6s memory now thebuild #ession@actory close the connection.
Note: callin build #ession@actory- method repeatedly in the project is
not recommended. It is recommended to call only once in life time of the
project.
$y default build #ession@actory- method is not cratin the tables. If you
want to hibernate to create the tables we have to supply an additionalproperty ;hbm' ddl.auto6 these properties can take any of the followin
four values create! update and createCdelete! validate.
&he followin is the ta which has to be added to Hibernate con3uration
3le.
Uproperty name P hbm'ddl.auto2MupdateUBpropertyM
It is always advisable to et a session =bject when ever we would like to
carry out any work by usin Hibernate. It6s always recommended to closethe session =bject after we 3nish the work. 8ettin a session object to
similar to ettin a connection object in 0D$".
4hen ever the session object is created immediately Hibernate starts a
cache object and it will be associated to session object are all this cache
objects as 1stlevel cache Hibernate remove the cache object when ever
we close the session object.
Arrays we have to start transaction after the session object is created.
4e need to start the transaction only for insertBupdateBdelete operation
only. 4e no need to start the transactions for retrieve the records.
4hen we call hsession save hibernate takes the object and add it to 3rst
level cache by usin a reistration code is &$#2 to be save.
eno: 1
name: abc
address:
8/9/2019 Hibernate (1) notes
16/691
"ache
4hen we call t5.commit2 hibernate ot 3rst level cache and check are
there any object are available in 3rst level cache it the objects are
available hibernate check. &he reistration code of the object hibernate
3nd to which 7=0= class this object is created and to which table this
7=0= class is mapped.
$ased on the table name and reistration and hibernate et the insert
%uery from the 0K(6s memory. It is the responsibility hibernates to
replace positional parameters with appropriate values from the object.
*ow the hibernate add the %uery to batch object.
*ow the hibernate send the batch object to Database server if it ot
e5ecute successfully it returns an identi3es value. If the batch is failed it
throws an e5ception batch update e5ception.
Hibernate send a s%l %uery to Database server to see the s%l %uery sent
by hibernate we can add property showCs%l2. &his attribute takes a
$oolean value.
Ex:
Uproperty name P showOs%l2MtrueUBpropertyM
&o see all the messaes are work done by hibernate we can use
lo+j.properties.
session
&$#
lo+j.root loer P DE$Y8BA1
lo+j.appender.A1 P or.A7Ache.lo+j.console
Appender
8/9/2019 Hibernate (1) notes
17/691
4e can use a method persist2 to store the data into database server.
'ntax: void persist-object
Ex: serialiXable save-object
4hen we enerate hbm 3les and 7=0= classes in hibernate by usin IDE
based on the column data type IDE enerate the appropriate data type in7=0= class for e5ample eno number-1/ IDE uses bi decimal data type
for eno number-' IDE uses byte and etc.
As part of java/. sun micro system as added a feature auto bo5in. &he
advantae of auto bo5in is we ?A* directly convert primitive data type
values to wrapper classes.
Ex:int a P 1N
inteer i P aN
system.out.println-iN
4hen we tryin to dual with auto bo5in for double data type as shown
below we are ettin the compilation error.
Ex: Double d P 'dN
develop a Hibernate application to retrieve a record from emp table
where eno is 'L
public class ,etrieve,ecordsR
public static void main-#trinVW arsR
"on3uration cf P new "on3uration-N
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N
#ession hsession P sf.open#ession-N
Emp e P new Emp-N
Hsession.load-e!new $idecimal-'N
#ystem.out.println-e.etEno-N
#ystem.out.println-e.et*ame-N
#ystem.out.println-e.et#alary-N
8/9/2019 Hibernate (1) notes
18/691
hession.close-N
S
S
4hen we call the load- method the internal code of Hibernate has
performed the followin steps.#tep 1: It has checked the correspondin 7=0= class name for the
supplied object.
#tep ': It has checked this 7=0= class object is mapped to which table for
that table Hibernate has picked appropriate select %uery. &he followin is
the %uery available in 0K(6s memory.
#elect eno! name! salary from emp where eno PL *ow the
Hibernate has replaced the positional parameter value with ' and
send the %uery to database server. Database server has e5ecuted the select %uery and represented the
records in the result set object and iven into hibernate software.
Hibernate software has taken from ,esult#et object and by usin
the etter method ot the data from ,esult#et object and stored it
in 7=0= class object. *ow the Hibernate added the 7=0= class object to 1stlevel cache.
Note: If we try to call a load cs method on a non available recordHibernate throw an e5ception sayin
;or.hibernate.=bject*ot@oundE5ception6.
&o check weather any object is available in 1stlevel cache or not we can
use a method ;contains-6.
'btax: boolean "ontains-object
4rite a hibernate application to delete the records from product table
whose productID is 11.&o delete the records from hibernate we can use
two approaches.
pproach *: ?oad the record and mark the object as to delete.
public class Delete,ecordsR
public static void main-#trinVW arsR
"on3uration cf P new "on3uration-N
8/9/2019 Hibernate (1) notes
19/691
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N
#ession hsession P sf.open#ession-N
&ransaction t5 P hsession.bein&ransaction-N
7roduct p P new 7roduct-N
hsession.load-p!11N BB step 1hsession.delete-pN BB step '
t5.commit-N BB step )
hsession.close-N
S
S
#tep 1: when step 1 is e5ecuted it has retrieve the records whose
primary key value is 11 and add into 1st
level cache.#tep ': 4hen we call the method object is marked as to be deleted.
#tep ): when we call the commit method the hibernate software ot the
delete %uery and replaces the positional parameter with primary key
value and send the %uery to database server.
In this approach 3rst we are checked in whether the record is available or
not if the record is not available. &he load- method throws object not
found e5ception.
pproach +: "reate the 7=0= class object and supply the primary key
value. (ark the 7=0= class object as to be deletin by callin the delete
method.
Ex:
public class Delete,ecords1R
public static void main-#trinVW arsR
"on3uration cf P new "on3uration-N
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N
#ession hsession P sf.open#ession-N
7roduct p P new 7roduct-N
p.setpid-11N
hsession.delete-pN
t5.commit-N
8/9/2019 Hibernate (1) notes
20/691
hsession.close-N
S
S
In this approach when we call the delete method object is marked as to
be deleted. 4hen we call the commit- method it has perform thefollowin ) steps.
#tep 1: It check weather primary key value is available in the supplied
object or not. If not available it will not carry out any work.
#tep ': If the primary key value is available a select %uery will be send to
database server to check weather record is available or not.
#tep ): If the record is available in D$ hibernate send the delete %uery. If
the record is not available hibernate will not do any work.
pproach *: Ypdatin a record into database server which ever the
record we would like to update load the record by callin load- method
modify the values by usin setter methods in the loaded 7=0= class
object. *ow mark the object as to be updated.
Ex:
public class Ypdate,ecordR
public static void main-#trinVW arsR"on3uration cf P new "on3uration-N
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N
#ession hsession P sf.open#ession-N
Emp e P new Emp-N
hsession.load-e! new $iDecimal-'N
e.set*ame-,aju2N
hsession.update-eN
t5.commit-N
hsession.close-N
S
S
8/9/2019 Hibernate (1) notes
21/691
pproach +: Hibernate uses a directory object techni%ue to check
weather object value is modi3ed or not. If the value is not modi3ed.
Hibernate will not send any update %uery to the database server. If the
values are modi3ed Hibernate send an update %uery to database server.
pproach ,: In this approach create 7=0= class object to the class whichwe would like to update the record and store the data into 7=0= class
object. 4e need to mark the object as to be updated.
Ex:
public class Ypdate,ecordR
public static void main-#trinVW arsR
"on3uration cf P new "on3uration-N
cf.con3ure-N
#ession@actory sf P cf.build#ession@actory-N#ession hsession P sf.open#ession-N
Emp e P new Emp-N
e.setEno-new $iDecimal-'N
e.set*ame-ttt2N
hsession.update-eN
t5.commit-N
hsession.close-N
SS
evict(): evict- method is used to remove a speci3ed object from the 1 s
level cache.
Ex:
&ransaction t5 P hsession.bein&ransaction-N
hsession.load-e!new $iDecimal-1N
e.set*ame-,aju2N
hsession.evict-eN
t5.commit-N
4hen we run the above application with out evict- method. It has
update a record into database server. 4hen we run the some application
8/9/2019 Hibernate (1) notes
22/691
with evict- method. It has removed employee object from 1st leve
cache.
merge(): mere method is used to add a speci3ed object to the 1 s
level cache.
Ex:Emp e P new Emp-N
e.setEno-new $iDecimal-''N
e.set*ame-A$" modi3ed2N
e.set#alary-1')+dN
hsession.mere-eN
t5.commit-N
4hen the mere- method is called the object is added to 1st
level cachewithout reistration code. 4hen t5.commit- method is called it will et
the object which does not contain the reistration code. It will check
weather the object is available in database server by sendin select
%uery. If the record is not available it will send an insert %uery to
database server. If the record is already available it will send a an update
%uery to database server.
&here three states are available to hibernate objects they are:
1. &ransient'. 7ersistent
). Detached
!ransient: An object is which is not associated with any session object.
Persistent: An object which is added to 1st level cache is called as
persistent state.
Detached: An object which is removed from 1st level cache is called
detached state.
$lear():
"lear is used to remove all the objects from 1 stlevel cache
&his will remove unperformed operations like save and update also. &he
clear- method will evict all available objects.
8/9/2019 Hibernate (1) notes
23/691
$onnection():
&his method is used to et leacy database connection.
8enerally this is not recommended approach in hibernate. 4e use this to
perform some operations which can not be done by usin hibernate.
Ex:
#ession hsession P sf.open#ession-N&ransaction t5 P hsession.bein&ransaction-N
"onnection con P hsession."onnection-N
#tatement stmt P con.create#tatement-N
stmt.e5ecuteYpdate-Insert into emp values-'!6sadaf6!')+2N
t5.commit-N
In Hibernate when we et the connection object by default auto commit
mode to false.4e have multiple over loaded methods as for session interface they are:
void load-object! pid
object load-class! serialiXable
Ex:
"lass c P class.for*ame-info.inetsolv.product2N
=bject o P hsession.load-c!lN
7roduct p P -productoN
#ystem.out.println-p.et7id-N#ystem.out.println-p.et*ame-N
#ystem.out.println-p.et7rice-N
4hen we call the above load- method if the record is available load-
method creates 7=0= class object and store the data and return 7=0=
class object if the record is not available load- method will not create
7=0= class object.
4e have a static variable class as part of object class when ever we call
that variable by usin class name it returns the callin class classobject.
Ex:
"one.class
4hen the above code is e5ecuted it has return class object.
name P
"one
packae Pnull
8/9/2019 Hibernate (1) notes
24/691
"lass
get():
et- method is also used to retrieve the record from database server if
the record is available it returns that 7=0= class object. If record is not
available it returns null value.
Ex:
=bject o P hsession.et-product.class!'N
If-oZ P nullR
7roduct p P -productoN#ystem.out.println-p.et7id-N
#ystem.out.println-p.et*ame-N
#ystem.out.println-p.et7rice-N
S
elseR
#ystem.out.println-,ecord is not available2N
S
-ush():
4hen we call in [ush- method all the objects which are
available in 1st level cache will be converted into %ueries and send to
database server. @lush will not store data permanently. 4hen we all the
commit- method the data is stored permanently.
Hbmadd?.auto property takes by diJerent values
1. Ypdate'. "reate). "reateCdrop+. Kalidate
8/9/2019 Hibernate (1) notes
25/691
If hbmaddl.auto P update and weather the build#essionfctory- method
is e5ecuted it checks weather tables are available or not. If not available
it create the takes.
If hbmaddl.auto P create if the tables are not available
build#ession@actory- method creates it. If the takes and create aain if
hbmaddl.auto P createCdrop if the tables are not available it creates thetables. when we close the session factory object the tables will be
dropped.
If hbmaddl.auto P validate! build#ession@actory- method check weather
the tables are present in the database server or not. If not available it will
throw an error messae missin table.
Developing Hibernate application b using manual procedure:
&he followin is an architecture of hibernate application.
#tep 1: "reate a table in the data base server.
#tep ': 8et the Hibernate software and placed in a lib folder -copy
ojdbc1+.jar also.
Note:
4e can et the jar 3les from IDE.
#tep ): Develop a cmd 3le which contains the class path to all the
Hibernate related jar 3les.
Ex: #et "?A##7A&HPlib\antlr.'...jarNlib\")7C.G.1.jarN
#tep +: "reate the 7=0= class. 4e can use any class name as 7=0= class
name for e5ample.
0ava application
Hibernate #B4
Hibernate.properties
or
Hibernate.cf.5ml
Database #erver
8/9/2019 Hibernate (1) notes
26/691
public class EmployeeR
int emp*oN
#trin emp*ameN
double emp#alaryN
public void setEmployee*o-int employee*oR
this.emp*o P employee*oN S
public int etEmployee*o-R
return empnoN
S
"reate hbm 3le the name of hbm 3le can be any thin.
UL5ml version P 1.2LM
UZ D="&7E hibernate.mappin public somethin2 http:BBwww.hibernate.orBdtdBhibernateCmappinC).dtt 2M
UhibernateCmappinM
Uclass name P info.inetsolv.Employee2table P emp2M
Uid name P employee*o2M
Ucolumn name P eno2BM
Uenerator class P assined2BM
UBidM
Uproperty name P employee*ame2MUcolumn name P name2BM
UBpropertyM
QQQQQQQQQQ.
UBclassM
UBhibernateCmappinM
Develop hibernate con3uration 3le.
UL 5ml version P 1.2LM
UZ D="&7E hibernateCcon3uration public hibernateCcon3uration2!
2http:BBwww.hibernate.orBdtdBhibernateCcon3urationC
)..dtt2M
UhibernateCcon3urationM
Usession factoryM
QQQQQQQQQQQ.
UBsession factoryM
http://www.hibernate.org/dtd/hibernate-mapping-3.0dtthttp://www.hibernate.org/dtd/hibernate-configuration-3.0.dtthttp://www.hibernate.org/dtd/hibernate-configuration-3.0.dtthttp://www.hibernate.org/dtd/hibernate-mapping-3.0dtthttp://www.hibernate.org/dtd/hibernate-configuration-3.0.dtthttp://www.hibernate.org/dtd/hibernate-configuration-3.0.dtt8/9/2019 Hibernate (1) notes
27/691
UBhibernateCcon3urationM
Develop a java application to store the data into database server.
&he parser proram check for hibernate dtd 3le as part of hibernate 3le.
As part of hbm 3le we can remove the column ta or attribute if the 7=0=
class properties and column names are same.
&he followin is sample con3uration for emp table.
UhibernateCmappinM
Uclass name P info.inetsolv.Employee2M
Uid name P employee*o2BM
Uproperty name P employee*ame2BM
Uproperty name P employee#alary2BM
UBclassMUBhibernateCmappinM
4e can club multiple hbm 3les into a simple hbm 3le. $ut this approach
is not recommended for bi projects! it is recommended to use one hbm
3le $r=ne one 7=0= class.
UhibernateCmappinM
Uclass name P info.inetsolv.Employee2MUclass name P info.inetsolv.7roduct2M
Uid name P 7id2 access P 3eld2BM
Uproperty name P name2 class P 3eld2BM
UBclassM
UBhibernateCmappinM
4e can develop hibernate application with out hibernate con3uration
3le. $ut we have to provide the properties and mappin 3les throuh the
java proram.
Ex:
public class #toreR
public static void main-#trinVW arsR
"on3uration cf P new "on3uration-N
cf.set7roperty-hibernate.connection.driverOclass2!2oracle.jdbc.driver.=r
acleDriver2N
8/9/2019 Hibernate (1) notes
28/691
cf.set7roperty-hibernate.connection.url2!2jdbc:oracle:thin:Tlocalhost:1
/'1:5e:2N
cf.set7roperty-hibernate.connection.username2!2hib2N
cf.set7roperty-hibernate.connection.password2!2abc2N
cf.set7roperty-hibernate.dialect2!2or.hibernate.dialect.=racleGDialect
2Ncf.set7roperty-hibernate.showOs%l2!2true2N
cf.add,esource-a.hbm.5ml2N
session@actory sf P cf.build#ession@actory-N
session hession P sf.open#ession-N
QQQQ
QQ..
Q.
SS
Instead of add,esource- method we can use add"lass- method.
Ex:
cf.add"lass-info.inetsolv.product.classN
when we use add"lass- it will check for info.inetsolv.product.hbm.5ml
3le.&he disadvantae of prorammatic con3uration is when Hard codin
the values in the java proram. If we want to communication with same
hibernate application with diJerent database server. 4e have to chane
the java code because of this reason this approach is not recommended.
8enerally in the projects we use properties 3les to remove hard codin.
(ost of the projects uses property 3le end with an e5tension dot -.
properties inside the properties 3le we supply a data in the form of key
and value.
Ex:
9ey P value BBmyproject.properties
4e can con3uration hibernate parameters as part of a propertyC3le.
4ho6s name is hibernate properties.
Ex:
hibernate.connection.driverOclass P oracle.jdbc.driver.=racleDriver
8/9/2019 Hibernate (1) notes
29/691
hibernate.connection.url P jdbc:oracle:thin:Tlocalhost:1/'1:5e
hibernate.connection.username P hib
hibernate.connection.password P abc
hibernate.dialect P or.hibernate.dialect.=racleGDialect
hibernate.showOs%l P true
BBsave hibernate.properties
It6s not recommended to use property 3le as part of hibernate. &his is
because as part of the property 3le are can6t con3uration the mappin
resource 3les.
4e can supply the values by the properties usin system properties
when we run the application.
Ex: CDhibernate.connection.driverOclass P oracle.jdbc.driver.=racleDriver
(eaerly hibernate is divided into three parts. &hey are:
Hibernate #B4
Hibernate #B4 is ood at =,( as well as transaction manaement the
internal hibernate code uses two connections pools ")7! D$"7. It6s not
recommended to use there connection pools. It6s always recommended
to use the e5ternal connection pool like weblogicconnection pool.
Ysin procedure to use webloic connection pool proram in hibernate.
1. "on3ure webloic server connection pool by specify 0*DI name.'. 8et the hibernate #B4 place in lib folder and set the class path.). "reate 7=0= class and hbm 3le.+. "reate hibernate con3uration 3le with data source! username and
password and jndi.class and jndi.urlUhibernateCcon3urationMU#essionC@actoryM
"onnection (anaement
=,(
&ransaction (anaement
8/9/2019 Hibernate (1) notes
30/691
Uproperty
namePhibernate.connection.datasource2MmypoolUBpropertyMUpropery
namePhibernate.connection.username2MadminUBpropertyMUpropery
namePhibernate.connection.password2MinetsolvUBpropertyMUpropery
namePhibernate.jndi.class2Mwebloic.jndi.4?Initial"onte5t@actory UBpropertyMUpropery
namePhibernate.jndi.url2Mt):BBlocalhost1BUBpropertyMUpropery namePhibernate.showOs%l2MtrueUBpropertyMUmappin resource P a.hbm.5ml2BMUB#essionC@actoryM
UBhibernateCcon3urationM/. Develop the hibernate application to store the data into database
server.Note: we have set the class path to web.jar or set DomainEnv.cmd
. 4hen we are con3uration are usin connection pool as part of
hibernate we have choose use jndi data source rather then jdbc
driver.. &o set the class path to resolve the problem of
webloic.jndi.4?Initial"onte5t@actory we are added webloic.jar in
the class path.F. Hibernate can be used to communicate with any D$ server.
Procedure to develop hibernate application to interact with
./'01:
4hen we communicate with (#>? D$ #erver. 4e have chane the url!
username! driver class and etc.
4e have to always use wrapper classes2 as part of 7=0= classes instead
of primitive data types. 7rimitive data types occupy less amount ofmemory when compared with wrapper classes. 7rimitive data types can6t
hold a null value.
Ex: public class (yAppR
public static void main-#trinVW arsR
int a P nullN
#ystem.out.println-aN
8/9/2019 Hibernate (1) notes
31/691
S
S
4hen we compile the above proram the compiler reports error messae
sayin null value can not be assined to primitive data types. we can
assined a null value to wrapper classes.
Ex: public class (yAppR
public static void main-#trinVW arsR
Inteer a P nullN
#ystem.out.println-aN
S
S
As part of the IDE when we eneratin hbm 3les and 7=0= classes wehave an option. 4e have primitive data types or wrapper classes. &hey
are java types and hibernate types.
4hen we choose java types it uses wrapper classes. 4hen we choose
hibernate types it uses primitive data types.
4e are try to use primitive data types and tryin to store data into
tables. In these scenarios the default values of primitive data types are
ettin store into data base server.
Ex:7roduct p P new 7roduct-N
p.set7id-7idN
p.set*ame-7nameN
hsession.save-pN
4hen we e5ecute the above code even thouh when the user is not
supplied price value application has stored . values.
4hen we use primitive data types to retrieve records from a table which
contains null values. then the application throwin an e5ception
org3hibernate3propertccessExcepton2.
$y usin 0D$" also we can represent the records in the form of objects.
&he followin is an e5ample of representin data in the form of object by
usin 0D$"L
Ex:
8/9/2019 Hibernate (1) notes
32/691
,esult#et rs P stmt.e5ecute>uery-select from product2N
Array?ist list P new Array?ist-N
4hile-rs.ne5t-R
7roduct p P new 7roduct-N
p.set7id-rs.etInt-1N
p.set7id-rs.et#trin-'Np.set7id-rs.etDouble-)N
list.add-pN
S
#ystem.out.println-After: ? A7I'. "riteria A7I). *ative s%l A7I
4hen we develop jdbc application to communicate with any database
server to remove the hard codin we use property 3les. As part of the
property 3les we have provided driver class! url! username! password
and %ueries. If we would like to communicate with other database
servers we chane the values from property 3les.
7roperty 3les
0D$" Application
Driver classurl
username!
password
D$ #erver
8/9/2019 Hibernate (1) notes
33/691
H>? %ueries as iven as input to hibernate #B4 it is the responsibility of
hibernate to convert H>? %uery into correspondin #>? %ueries and send
into data base server.
Hibernate uys has provided so many direct classes. As part of this
dialect classes the code is provided to convert H>? %uery to
correspondin s%l %ueries.
&he dialect classes are available in org3hibernate3dialectpackae. &he
followin are some of the dialect classes. =racle dialect! (y#%l dialect!
#A7 dialect etc.
&he followin are the features of s%l.1. H>? >ueries fully object oriented.'. H>? >ueries supports inheritance and poly morphism.). H>? >ueries are case sensitive.
If we want to write H>? %ueries instead of table names we have to use
7=0= calss names.
Instead of column names we have to use property names H>? %ueries
derived from s%l %ueries. &he followin is H>? %ueries derived from s%l
%ueries. &he followin is H>? and s%l %ueries to retrieve all the recordsfrom emp table.
#>?M select from empN
&able name
H>?M from info.inetsolv.Employee
7=0= calss name
0ava proram usin H>?
Hibernate #B4
=racle (y#%le D$'
8/9/2019 Hibernate (1) notes
34/691
Develop a hibernate application which uses H>? %ueries to retrieve all
the records from emp table.
Procedure to use H01 in herbernate:
1. ,epresent H>? %uery in the form of %uery object.
'. #end the %uery object to hibernate software by callin the listmethod.
). Hibernate #B4 returns an Array?ist object render the Array?ist
object and display the output to client.+. >uery is an interface which is available as port of or.hibernate
packae. 4e can not create the object to %uery interface. 4e can
create a reference variable and it holds implementation class
object.
public class ,etrieveDataR
public static void main-#trin arsVWR
BB #tandard code
#ession hsession P sf.open#ession-N
>uery %uery P hsession.create>uery-h%l %ueryN
?ist l P %uery.list-N
Array?ist emplist P -Array?istlN
Iterator i P emplist.iterator-N
while-i.has*e5t-REmployee e P -EmployeeN.ne5t-N
#ystem.out.println-e.etEmployee*o-N
#ystem.out.println-e.etEmployee*ame-N
#ystem.out.println-e.etEmployeeAddress-N
S
hsession.close-N
S
S
4hen we call the list- method the followin steps are carried out by list-
method.
1. H>? %uery will be converted into correspondin #>? >uery.'. Hibernate #B4 send #>? %uery to database server.
8/9/2019 Hibernate (1) notes
35/691
). &he database server e5ecutes select %uery and return the ,esult#et
object to hibernate #B4.+. Hibernate #B4 represents every record in the form of object and add
it to array list object./. ?ist- method converts Array?ist into supper class reference variable
list and it returns it we have to et Array?ist object and displayrecords to client.
4hen we tryin to add any element to Array?ist object it will be
converted into supper class object called as object. 4hile retrievin data
from Array?ist we need to typecast into appropriate object.
As part H>? %ueries we can add where conditions as well as order by
clause! roup by clause.
using where clause as part o H01:
#>?M select from emp where enoM'N
H>?M from info.inetsolv.Employee where employeeM'N
using positional parameters in H01:
&he followin is an e5ample of usin positional parameters in H>?.
#>?M select from product where price ML And priceUL
H>?M from product where priceML And priceML
Ex:
#trin %uery P from product where priceML And priceUL2N
>uery h%l%uery P hsession.create%uery-%ueryN
h%l%uery.#etDouble-!'N
h%l%uery.#etDouble-1!/N
Array?ist ?ist P -Array?isth%l%uery.list-N
In hibernate the H>? %uery positional parameter inde5 starts with .
If we do not supply the values to all positional parameters hibernate
display an e5ception %uery e5ception.4e can use alias names as part of H>? %uery by usin a keyword as.
Ex:
#trin %uery P from product as p where p.priceML and p.priceUL2N
4e can use order by as part of H>? %ueries.
Ex:
8/9/2019 Hibernate (1) notes
36/691
from product order by price desc
%etrieving specifc columns rom emploee table:
&he followin e5ample et employee*o! employee*ame columns only
from the database server.
#trin %uery P select employee*=!employee*ame frominfo.inetsolv.Employee2N
>uery h%l %uery P hsession."reate>uery->ueryN
Arraylist ?ist P -Arraylisth%l>uery.?ist-N
Iterator i P list.iterator-N
4hile-i.has*e5t-R
=bject oVW P -objectVWN
*e5t-N
BBcode to display the data from arrays usin inde5.for-int jPoNjU.lenthNjuery %ue P hsession."reate>uery-%N
1
' etwo
Inteer
Inteer
1
eone
etwo
'
A
,
,
A
?
I
#
&
8/9/2019 Hibernate (1) notes
37/691
Array?ist list P -Arraylist>uery.?ist-N
Iterator i P list.iterator-N
while-i.has*e5t-R
=bject o P i.ne5t-N
Inteer ii P -InteeroN
#ystem.out.println-iiNS4hen we have only one column in the select clause as part of the array
list the data type will be added.
#trin
#trin
#trin
#trin
rs
4e can use areate functions in H>? %ueries. &he followin is an
e5ample usin H>? to 3nd number of records available in product table.
#trin % P select count- from product as p2N
>uery %ue P hsession."reate>uery-%N
Array?ist list P -Array?ist%ue.?ist-N
Iterator i P list.iterator-N
while-i.has*e5t-R
=bject o P i.ne5t-N
?on l P -?onoN
#ystem.out.println-oN
S
eone
etwo
ethree
efour
eone
etwo
ethree
efour
A
,
,
A
?
I
#
&
8/9/2019 Hibernate (1) notes
38/691
4e can join multiple tables and retrieve the records the followin is an
e5ample of join tables.
>uery H>?%uery
Array list P -ArraylistH>?%uery.?ist-N
Iterator :P list.iterator-N
while-i.has*e5t-R=bject oVW P -objectVWi.ne5t-N
for-int jPNjU.lenthNjuery h%l>uery P hsession.create>uery->ueryN
h%l>uery.set#trin-!25yX2N
h%l>uery.setInteer-1!1N
int no P h%l>uery.e5ecuteupdate-N
#ystem.out.println-noN
t5.commit-N
hsession.close-N
S
S
Note:
4hen we perform update! delete and insert operations. 4e must
place the code in a transaction.
8/9/2019 Hibernate (1) notes
39/691
H%l will not support to insert record directly into table. if the data is
already available in table we can copy from one table to another table.
&ransaction t5 P hsession.bein&ransaction-N
#trin >uery P insert into
Employee-employee*o!employee*ame select pid! name
from product2N>uery h%l >uery P hsession.create>uery->ueryN
int no P h%l >uery.e5ecuteupdate-N
#ystem.out.println-noN
t5.commit-N
hsession.close-N
S
Named positional parameters:4hen we write the h%l >ueries we can use positional
parameters the problem with positional parameters is if somebody tryin
to read and understand it takes lot of time. Instead of positiona
parameters we use names. &his will improve the readability of the
%ueries.
*amed positional parameters will not improve performance separately.
&his is because by default named positional parameters also uses
prepare statements. &he followin is an e5ample of named positionalparameter.
Ex:
@rom product where priceM:min value and priceU:ma5 value. &he
followin is an e5ample of usin named positional parameters.
#trin >uery P from product where priceM:minvalue and
priceU:ma5value2N
>uery h%l >uery P hsession."reate>uery->ueryN
h%l >uery.setDouble-minvalue2!'N
h%l >uery.setDouble-ma5value2!N
Arraylist list P -Arraylisth%l>uery.?ist-N
In hibernate to retrieve the data from all the tables we can use h%l %uery
like from java.lan.object
Ex:
8/9/2019 Hibernate (1) notes
40/69
8/9/2019 Hibernate (1) notes
41/691
Hibernate uys has iven prede3ned classes to add the restrictions. &hey
are available as part of or.hibernate.criteria packae some of the
important classes in that are restrictions!order! property etc.
&he followin is code to add restrictions to criteria.
"riteria c P hsession.create "riteria-7roduct.classN
c.add-,estrictions.e-price2!'dNc.add-,estrictions.le-price2!+dN
&he ,estrictions class contains couple of static factory methods. &he
internal code of these methods add- the where conditions to the >uery
as a developer we are responsible to use these methods based on the
re%uirements.
&o sort the records based on "riteria A7I they have provided prede3nedclasses like order. &his contains the methods like asc! desc.
Ex:
"riteria c P hsession."reate "riteria-product.classN
c.add=rder-order.desc-price2N
&o retrieve the speci3c columns from the data base table we use
projections class.
Ex: "riteria c P hsession."reate "riteria-product.classN
c.set7rojection-7rojections.property-name2N
4hen we run the above java proram the Array list object contains the
columns correspondin data type.
adding multiple projections:
"riteria c P hsession."reate "riteria-7roduct.classN
7rojection?ist pl P projections.7rojection?ist-N
7l.add-7rojections.property-name2N
7l.add-7rojections.property-pid2N
c.set7rojection-plN
Note:
8/9/2019 Hibernate (1) notes
42/691
"riteria A7I is not best sui table for the real time projects and to
develop complicate >ueries for e5ample usin the functions like di code!
nul1! nul' etc.
Native '01 PI:
&he main advantae of *ative #>? is we can write data basespeci3c >ueries as part of hibernate. $y usin *ative #>? A7I we can
perform the operations like insert >uery! update! delete! retrieve and call
the procedures and etc.
&he followin is an e5ample of callin the procedure by usin *ative #>?.
Ex:
&ransaction t5 P hsession.bein&ransaction-N
#>? >uery >uery P hsession.crete#>?>uery-Rcall myprocS2N
>uery.e5ecuteYpadate-Nt5.commit-N
How do we use hibernate in web based applications4
How do we use hibernate in sturts4
1. "reate a web based application.'. "opy all the hibernate related jar 3les into project lib folder.). "opy hibernate con3uration 3le! 7=0= classes! hbm 3les and
hibernate con3uration 3les into classes folder.
+. "reate hbm 3le and servlet to capture data and store data.
5enerators:
In all the applications which we developed as of new end user is suppose
to enter the primary key values.
It is not recommended to ask the end user to enter to enter the primary
key values. It6s always recommended to enerate primary key values by
the application. &his resolves the problem of end user rememberin the
primary keys.$y usin 0D$" we have to write code to enerate primary key values. If
we use hibernate internally it contains a loic to enerate the primary
key values.
pproach*:
8/9/2019 Hibernate (1) notes
43/691
In this approach we 3nd the ma5imum values from correspondin table
and increment by one and use it as primary key value to 3nd the ne5t
primary key value we can use the followin %uery.
Ex:
#elect ma5-eno < 1 from empN
&his loic can be used in any data base server.
pproach+:
=racle data base server supports a feature se%uences to enerate the
primary key values to create the se%uence we use the followin %uery.
Ex:
create se%uence empse%
min value 1
ma5 value GGGGGincrement by 1
start with 1N
&o see all the available se%uences in the data base server. 4e use the
followin %uery.
#>?M select from userOse%uencesN
pproach,:In mys%l there is a feature auto increment. If we use it mys%l itself will
increment the primary key values.
&o use auto increment at the time of table is created we must specify
auto increament.
Ex:
create table product-pid int-/ primary key autoOincreament!
name varchar-'!
price decimal-1N
&o insert the values we use the followin %uery.
Ex: insert into product-name!price values-;abc6!++/N
auto increment will write in mys%l and D$'. It does not work in oracle.
Hibernate has iven set of prede3ned classes to deal with primary key
values. &hese classes are available in a packae. or.hibernate.id2
8/9/2019 Hibernate (1) notes
44/691
&he followin are some of the classes of hibernate enerators.
1. Assined'. #e%uence enerator). Increment enerator+. uuid enerator/. uid enerator etc.
Hibernate uys has iven an interface identi3er enerator this contain a
method enerator.
All the above enerator classes must provide implementation to an
interface identi3er enerator. As part of the enerate method the loic isprovided to enerate the primary key value. &his method returns primary
key value in the form of serialiXable object.
As part of the hbm 3le there is a ta enerator. &his specify the
enerator which has to be used by hibernate.
E6:
Uenerator class P or.hibernate.id .#e%uence 8enerator2BM
Hibernate uys has provided short names for every enerator. 4e can
use the short names on be half of class names. &he followin are some ofthe short names. Assined! se%uence! increment! native! hilo! uuid etc.
&he followin is an e5ample of usin short names.
Uenerator class P se%uence2BM
$efore we use a enerator we have to check the followin two steps.
1. 4eather this enerator can be used in the correspondin data base
server or not.
'. 4e need to check weather the enerator supports speci3c datatype or not.
ssigned generator:
4hen we use assined enerator hibernate e5pect us to supply primary
key value by default when we enerator hbm and 7=0= classes enerator
is assined with assined value.
Identi3er enerator
#erialiXable enerate-QQQ
8/9/2019 Hibernate (1) notes
45/691
In the hbm 3le we can use enerator with hibernate class name or short
name.
Uid name P pid2 type P inteer2M
Ucolumn name P pid2BM
Uenerator class P or.hibernate.id.Assined2BMUBidM BB product.hbm.5ml
=,
Uid name P pid2BM
Ucolumn name P pid2BM
Uenerator class P assined2BM
UBidM
In the hbm 3le if we does not supply the enerator ta by default
hibernate consider assined enerator.
If we supply a wron class name or invalid enerator class name
hibernate throw an e5ception could not instantiate id enerator.
Increment generator:
4hen we use this enerator it will increment the primary key valueby one based on e5istin primary key value. &his alorithm internally
uses the e5istin primary key value.
4hen we use this alorithm it will use the followin %uery to 3nd the
ma5imum primary key value.
Ex: select ma5-pid from product
&he followin is the con3uration of increment enerator.
Uenerator class P or.hibernate.id.Increment 8enerator2M
UBeneratorM
Uenerator class P Increment2M
UBeneratorM
Increment enerator can enerate the primary key values for short! lon!
inteer data types only.
4e can use increment enerator in mys%l data base server also.
8/9/2019 Hibernate (1) notes
46/691
Identi generator:
&his enerator can be used only in mys%l data base server to use
this enerator compulsory the table must be auto increment. &he
followin is the con3uration of identify enerator.
Uenerator class P or.hibernate.id.dentity enerator2BM
=,Uenerator class P identity2BM
(se&uencehilo):
'e& hilo: &his enerator uses both se%uence as well as hilo value to
enerator a primary key value. &his is same as hilo enerator. this uses
the se%uence instead of table. the followin is the con3uration for
se%uence hilo enerator.
Uenerator class P se%hilo2MUparam name P se%uence2Mpidse%UBparamM
Uparam name P marOlo2M/UBparamM
UBeneratorM
7uid8guid: &hese enerators enerate the primary key value based on
the I7 address of the system and the start up time of 0K( and convert it
into )' bit he5adecimal number and store in data base server.
&o work with uidBuuid enerators the primary key value data type mustbe var char with minimum siXe of )' bit. &he followin is the
con3uration of enerator.
Uenerator class P uuid2BM
Instead of prede3ned enerator we can use our own enerator also to
et the primary key values.
&o develop our own enerator class it must provide implementation to
interface identi3er enerator. In this we need to provide the
implementation to enerator method.
Ex:
public class =ur=wn8enerator implements Identi3er 8eneratorR
public serialiXable enerator-#essionImplementor session! object
objectR
int eno P N
8/9/2019 Hibernate (1) notes
47/691
,esult#et rs P
session.etbatcher-.7repare$atch#tatement-select ma5-eno
from emp2.e5ecute>uery-N
if-rs.ne5t-R
eno P rs.etInt-1N
eno P eno < 1NS
return enoN
S
S
&o use this enerator in hibernate we have to con3ure it in hbm 3le as
show below.
Ex: Uenerator class P info.inetsolv.ourown 8enerator2BM
4hen we use hibernate in form based applications we have provided thecon3ure method and build session factory method as part of service
method.
'ingle ton design pattern:
&he main purpose of sinle ton desin pattern is it make sure that
any work e5ecute only once or it make sure that the object is created to
a class only once.
&he followin "one class makes sure that it creates only one object formultiple people.
public class "oneR
private static "one cN
#taticR
#ystem.out.println-creatin "one object only once2N
c P new "one-N
S
public static "one create "one object-R
return cN
S
7rivate "one-R
#ystem.out.println-"one object is created2N
S
S
8/9/2019 Hibernate (1) notes
48/691
&o et the "one class object we use a method created "one object
public class (yApp-R
public static void main-#trin arsVWR
"one c1 P "one.create "one object-N"one c' P "one.create "one object-N
#ystem.out.println-c1N
#ystem.out.println-c'N
S
S
&he followin is hibernate sinle ton desin pattern. &his class make sure
that session factory is created only once.
public class Hibernate #ession@actory#inle&onRprivate #tatic #ession@actory sf P nullN
#taticR
"on3uration cf P new "on3uration-N
cf.con3ure-N
sf P cf.build#ession@actory-N
S
public #tatic #ession @actory et#ession@actory-R
return sNS
private Hibernate#ession@actory#inle&on-R
S
S
As part of a servelet we et the session object directly from sinle ton
desin pattern.
Ex: public class #tore7roduct#ervlet e5tends Http#ervletR
public void service-. . . . . . R
#ession hsession P Hibernate#ession factory sinle ton .
et#ession-N
. . . . . . . .
. . . . . .
. . . .
8/9/2019 Hibernate (1) notes
49/691
hsession.close-N
S
S
&he followin is an e5ample hibernate temple desin pattern. $y usin
this any body can perform the some operation by usin one line.
Ex:public static void save-object oR
#ession hsession P Hibernate session factory.et#ession-N
hsession.bein&ransaction-N
hsession.#ave-oN
hsession.et&ransaction-.commit-N
Hibernate session factory.close #ession-N
S
SDevelop a servlet to et a all the records from product table and display
to the client.
Named 0ueries:
*amed >ueries will improve the performance of java application.
4hen we develop a web based application to retrieve the records from
product table and display to the client by usin H>? >ueries every time it
try to convert H>? >uery into correspondin #>l >uery. 4e can improve
the performance of by usin named >ueries.
Procedure to use Named 0ueries:
1. "on3ure *amed >ueries as part of hbm 3les.Ex: UhibernateOmappinM
UclassCCC MCCCCCCCCC MUBclassMU%uery name P pd2Mfrom
info.inetsolv.productUB%ueryMUBhibernateOmappinM BBproduct.hbm.5ml'. @rom the java application to use the *amed >ueries use a
method.et*amed>uery->uery %uery P hsession.et*amed>uery-pd2NArray?ist al P -Array?ist%uery.list-NIterator i P list.iterator-N
8/9/2019 Hibernate (1) notes
50/691
4hen we are usin *amed >ueries we can supply named positional
parameters also.
Ex: U%uery name P pd2Mfrom info.inetsolv.product where name P:
nameUB%ueryM
*amed native #>? we can con3ure native #>? also as part of hbm 3les.&o con3ure native s%l we use a ta Us%lO%ueryM
Ex:
UhibernateOmappinM
UclassCCCCCC M
CCCCCCCCCC
UBclassM
Us%lO%ueryMname P hs%l2M select from product UBs%lO%ueryM
UBhibernateOmappinM
&o call named s%l from java application we use a et*amed >uery this
returns %uery object. 4hen this send to data base server we etArray?ist
object with objectArray as the values.
Ex: >uery %uery P hsession.et*amed>uery-hs%l2N
Array?ist al P -Array?ist%uery.list-N
Iterator i P al.iterator-N
while-i.has*e5t-Robject oVW P -objectVWi.ne5t-N
for-int jPNjUP.lenthNj
8/9/2019 Hibernate (1) notes
51/691
public class 0D$"4ork implements worksR
public void e5ecute-connection conR
"allable#tatemet cstmt P con.7repare"all-Rcall myprocS2N
cstmt.E5ecute-N
S
S4hen we write the business loic in the procedure they will improve the
performance. &he disadvantae of this approach. If we chane the data
base server the application will not work as a java prorams we
recommend to write the business loic in java application.
Hibernate is not the best solution when we write the business loic
in procedure. It6s not recommended to use procedures in the projects
which uses hibernate. 4e are seen three approaches of callinprocedures from hibernate.
1. $y ettin the connection from session object.'. $y usin native #>? application.). $y usin do work method.
4hen we use do work method hibernate internally uses callback
mechanism to call e5ecute method the advantae of this is we are not
openin the connection we are not closin the connection. A procedure
can write multiple records to achieve this we have to use cursors in
procedure.
"ursors are a temporary memory area. 4here the records will be stored
the cursor object will be created by oracle. 4hen ever select %uery is
e5ecuted in oracle they are two types of cursors available. &hey are:
1. Implicit cursors'. E5plicit cursors
&he followin procedure returns a cursorB,esult#et object create or
replace procedure (y7roc- rs out sysOrefcursor
As
$ein
open rs for select from productN
end myprocN
8/9/2019 Hibernate (1) notes
52/691
B
@ollowin java application to call the procedure and display to the client.
public class 8et,ecordsR
public static void main-#trin arsVWR
BBstandard jdbc code
"allable#tatement cstmt P con.7repare"all-Rcall myproc-LS2Ncstmt.E5ecute-N
,esult#et rs P -,esult#et cstmt.et=bject-1N
BBcode to display the records
S
S
Hibernate uys are ivin a way to call procedure which takes a
parameter refcursor.
"on3ure procedure in hbm 3le as shown below.UhibernateOmappinM
Uclass CCCCC M
CCCCCCCCCC
UBclassM
Us%lO%uery name P cp2 callable P true2M
Ureturn class P info.inetsolv.product2MUBreturnM
Rcall myproc-LS
UBs%lO%ueryMUBhibernateOmappinM
&o call the procedure from java we use named %ueries as shown below.
>uery %uery P hession.et*amed>uery-cp2N
Arraylist al P -Arraylist%uery.list-N
Iterator i P al .iterator-N
while-i.has*e5t-R
product p P -producti.ne5t-N
S
S
4e have to follow limitations in hibernate to call the procedure.
1. &he 3rst parameter procedure must be out parameter and the data
type must be ref cursor.'. 4hen we are con3urin the procedure in we must use on attribute
callable st.
8/9/2019 Hibernate (1) notes
53/691
4hen we specify callable true hibernate reister. &he 3rst parameter as
out parameter we must use native s%l to call the procedure from
hibernate application.
If you want to search the records based on iven product id you have to
supply a product id as parameter to procedure. 4e can call that thecon3ure in hbm 3le as shown below.
4e can develop a hibernate software to
communicate with multiple data base servers from a sinle project
7rocedure to use hibernate with multiple data base servers for the same
project. "reate multiple hibernate con3uration 3les.
Ex:
hibernate.cf.5mlhibernate.mys%l.cf.5ml
&o use multiple data base servers in the project we use multiple
con3uration 3les and multiple session factory objects. In the projects we
do this work only once by usin a sinle ton desin pattern only.
public class Hibernate#ession@actoryR
private static #ession@actory osf P nullN
private static #ession@actory msf P nullNstaticR
"on3uration ocf P new "on3uration-N
ocf."on3ure-N
"on3uration mcf P new "on3uration-N
mcf."on3ure-hibernate.mys%l.cf.5ml2N
ocf.build#ession@actory-N
mcf.build#ession@actory-N
S
public static #ession@actory et mys%lsession@actoryR
return ocfN S
public static #ession@actory et mys%lsession@actoryR
return mcfN S
private Hibernate#ession@actory-RS
8/9/2019 Hibernate (1) notes
54/691
In the java application we et the re%uired #ession @actory object and
perform the operations.
Ex: #un (icro #ystem has released 07A A7I to interact with data base
servers they are released this A7I as part of 0EE standard A7I.
&he followin is the classes and interfaces as part of 07A.
$lasses Interaces 7ersistence
Hibernate uys provided the implementation to 07A A7I.
"reate a java project and add 07A capabilities. &here are so many people
who are providin the implementation same of them or top link!
hibernate and open 07A and etc. we can use any jar 3les to develop 07A
application. 4hen we add 07A capabilities it has created an 5ml 3le
whose name is persistence.5ml in this we have speci3ed persistence unitname.
8enerate an Entity $eans -7=0= classes. Develop a java
application to store the data into employee table.
public class #toreEmpR
public static void main-#trin arsVWR
Entity(anaer@actory emf P
7ersistence."reateEntity(anaer@actory-07A=,A"?E72NEntity(anaer em P emf."reateEntity(anaer-N
Entity&ransaction t5 P em.et&ransaction-N
t5.bein-N
Emp e P new Emp-N
e.setEno-1N
e.setEno-'N
e.setEno-)N
em.7ersist-eN
t5.commit-N
em.close-N
S
S
8/9/2019 Hibernate (1) notes
55/691
&he top link provides the implementation of 07A A7I to work with top link
we are to download the top link jar 3les and set the class path. 4hen we
are developin a project at the desin phase we try to develop two types
of desin.
1. Data base desin
'. 0ava desin
As part of data base desin we will decide the names of the tables and
columns of the tables and etc. At the time of developin the project
developer will not create any tables. In most of the projects we have to
capture multiple address to an employee.
Eno
*ame
Address:
#treet city state
ADD another address
&o implement above re%uirement we ot the followin desin.
Design *:
As part of desin we are addin two tables. Emp table and address table
in the Emp table Eno is a primary key. In the address table Eno! Address
no are formin the primary key.
Design +:
1
Am pet
*aidu
HD
HD
#,
A7
A7
#tore
Eno *ame #treet #tate
"ity
Eno-79 *ame
salary
Eno Addno #treet #tate
"ity
8/9/2019 Hibernate (1) notes
56/691
In the desin' the address table contain Eno! addressno as primary keys.
If more than one column in valued in formin a primary key we call it ascomposite primary key. Hibernate will not ive the best performance if
the table contains composite primary key. Hibernate ive the best
performance if it6s havin only one primary key.
Design ,: In this desin we have two tables. &hey are emp and address.
In the address table we will try to have a new column which acts as
primary key.
8enerally by usin hibernate we should be able to create the tables. but
accordin to the project desin 3rst we are creatin tables from the
tables we are creatin 7=0= classes. "reatin the 7=0= classes from the
table is called as hibernate reverse enineerin.
&here are some situations where we need to develop hibernate
applications based on leacy data base servers.
4hat are leacy data base serversL
&he data base server which uses composite primary key6s is called as
leacy data base servers. 7rocedure to develop hibernate applications
based on leacy data base. "reate the followin the two tables.
!able *: create table emp-eno number-/ primary key!
*ame varchar'-'! salary number-1!'N
Eno-79 *amesalary
1 *aidu
Aid Eno-79 addno #treet #tate
"ity
1 1 1 A7et HD
A7
8/9/2019 Hibernate (1) notes
57/691
!able +: create table address-eno number-/! addrno number-/!
#tate varchar'-'! primary key-eno! addrnoN
4hen we enerate hbm 3les and 7=0= classes we have observed that )7=0= classes and two hbm 3les the 7=0= classes are:
Emp.java
AddressId.java
Address.java
4e have not observed any chane in emp 7=0= class. &his is because
this table is havin only one primary key. 4e have observed that address
table is created. &wo 7=0= classes:
1. "omposite primary key class-AddressId'. ,eular 7=0= classes
&he composite primary key class contain two properties this is because
two columns involvin in formin composite primary key.
public class AddressIdR
Inteer EnoN
Inteer addrnoN
BBsetters and etters
S
&he followin is address.java which uses composite primary key class asa property.
public class AddressR
AddressId idN
#trin streetN
8/9/2019 Hibernate (1) notes
58/691
#trin cityN
#trin stateN
BBprovide setters and etters S
4e are enerated two hbm 3les. &hey are:
1. Emp.hbm.5ml'. Address.hbm.5ml
4e have not observed any chanes in Emp.hbm.5ml 3les. 4e have
observed lot of chanes in address.hbm.5ml 3le with respect to
composite primary key.
UhibernateOmappinM
Uclass name P info.inetsolv.Address2 table P Address2M
UcompositeCid name P id2 class P info.inetsolv.AddressId2M
UkeyCproperty name Eno2M
Ucolumn name P Eno2BM
UBkeyCpropertyM
UkeyCproperty name P addno2M
Ucolumn name P Addno2BM
UBkeyCpropertyMUBcompositeCidM
Uproperty name P street2BM
Uproperty name P city2BMUproperty name P state2BMUBclassM
UhibernateOmappinM
&he followin java application to store the data into data base server
creatin the emp obj.
8/9/2019 Hibernate (1) notes
59/691
1. AddressId obj'. Address obj). "all save method for emp.address
&o establish the relationship between tables we do it based on the data
available in the tables. &hey are:
1. =ne to many'. (any to one). =ne to one+. (any to many
&o establish the relationship between tables we do it based on the data
available in the tables.
"ne to man relationship:
&o identify the relationship between the two tables we use the data
based on the data available in the tables develop a hibernate application
which uses oneCtoCmany relationship bBw emp and address table. &he
followin of the two tables are created by emp and address.
create table emp-Eno number-/! *ame varchar'-'! salary
number-1!'N
create table emp add primary key-EnoN
create table address-Aid number-/! Eno number-/! Addno number-/!
city varchar'-1N
alter table address add primary key-AidN
create table address-Aid number-/ primary key! Eno number-/
references emp-Eno
when we enerate hbm 3les and 7=0= classes we ot two hbm 3les and
7=0= classes. &he followin is the 7=0= class from emp table.
public class empR alter table address add
Inteer EmpN forein key-Eno references
8/9/2019 Hibernate (1) notes
60/691
#trin nameN emp-EnoN
Double salaryN
#ent address P new Hash#et-N
BBprovide settin and etters
S
&he followin is the con3uration of the Emp.hbm.5ml represents the
many relationship.
UhibernateOmappinM
Uclass name P info.inetsolv.Emp2M
Uid name P Eno2BM
Uproperty name P name2BM
Uproperty name P salary2BM
Uset name P address2 inverse P true2M
UkeyM
Ucolumn name P E*=2BM
UBkeyM
UoneCtoCmany class P info.inetsolv.Address2BM
UBsetM
UBclassM
UhibernateOmappinM
&he followin is the 7=0= class for Address table.
public class AddressR
Inteer aidN
8/9/2019 Hibernate (1) notes
61/691
Emp empN
Inteer addnoN
#trin streetN
#trin cityN
#trin stateN
BB provide settress and ettress
S
&he followin hbm 3le for address table.
UhibernateOmappinM
Uclass name P info.inetsolv.Address2M
Uid name P aid2BM
UmanyCtoCone name P E(72 class P info.inetsolv.Emp2M
Ucolumn name P E*=2BM
UBmanyCtoConeM
Uproperty name P addrno2BM
Uproperty name P street2BM
Uproperty name P city2BM
Uproperty name P state2BM
UBclassM
UBhibernateOmappinM
8enerally IDE reconiXe the relationship between tables and enerate
hbm 3les and 7=0= classes. Hibernate understand the relationship
between the tables based on the tas which are available in hbm 3le. &o
8/9/2019 Hibernate (1) notes
62/691
represent many relationship in hibernate we use collection objects. &he
followin are collection objects of hibernate.
?ist #et (ap $a
&hese collection objects represents many relationships we use hibernate
from the java side we have to create the objects store the data intoobjects and establish circular relationship.
one
Emp Address
Hashtable
&he followin java application to store the data into emp as well as
address table.
public class storeR
public static void main-#trin strVWR#ession h P Hibernate#[email protected]#ession-N
&ransaction t5 P h.bein&ransaction-N
Emp e P new Emp-N
e.#etEno-1N
e.#et*ame-*aidu2N
e.#et#alary-1!N
Eno P null
*ame P null#alary P
null
Address
#iXe P1
Emp
aid P nullaAddrno P
null
city P null
state P
null
8/9/2019 Hibernate (1) notes
63/691
Address a P new Address-N
a.#etAid-1N
a.#etEmp-eN
a.#etAddno-1N
a.#et"ity-HD2N
a.#et#tate-A72N#et s P e.etAddress-N
s.add-aN
h.#ave-eN
h.et&ransaction."ommit-N
Hibernate#ession@actory."lose#ession-N
4hen we call save-e hibernate can 3nd the relationship between thetables and store the data into dependent on tables to do this we must
specify two attributes inverse and cas code.
U#et CCCCCCCCCCC inverse P true2 cascade P all2BM
Develop a java application to retrieve the data from emp table who emp
no is ' -we would like to retrieve the correspondin address details.
Hibernate checks two strateies to retrieve the record from data base
server.
1. ?aXy loadinCCCCCCM Arisive -eaer loadin.
4hat is laXy loadinL
4hen ever we perform can operation on one table and table has
relationship with other tables and then we called a load method it will
retrieve the data from that table only.
Hibernate retrieve the records from child table when even any operation
is carried out of any other table. $y default hibernate uses laXy
loadin-true.
4hat is Aressive loadinL
4hen ever we call a load method on a parent table it will try to retrieve
record form child table also even thouh user doesn6t access any
properties. How to make hibernate as aressive we have to con3ure
laXy P false2 in hbm 3le of parent table.
8/9/2019 Hibernate (1) notes
64/691
Uset CCCCCCCCCC inverse P true2 laXy P false2M
UBsetM
&he followin is the e5ample of retrieve the data from data base server
by usin the load- method which is loadin the relationship.
public class ,etrieveR
public static void main-#trin arsVWR#ession s P Hibernate#[email protected]#ession-N
Emp e P new Emp-N
e.etEno-N
e.et*ame-N
e.et#alary-N
#et address P e.etAddress-N
#ystem.out.println-address.#iXe-N
Iterator i P addresses.iterator-Nwhile-i.has*e5t-N
Address a P -Addressi.ne5t-N
#ystem.out.println-a.etAid-N
#ystem.out.println-a.etAddno-N
#ystem.out.println-a.et"ity-N
S
Hibernate#[email protected]#ession-N
SAs part of 7=0= classes and hbm 3le instead of set we can use only
hibernate type ?ist! map! set! ba.
Ex: 4e are usin the list in the emp table is shown below.
public class EmpR
Inteer enoN
#trin nameN
Double salaryN
?ist address P new Array?ist-N
S
&he followin con3uration of Emp.hbm.5ml
UhibernatOmappinM
Uclass name P info.inetsolv.emp2M
Uid name P Eno2BM
Uproperty name P name2BM
8/9/2019 Hibernate (1) notes
65/691
Uproperty name P salary2BM
Ulist name P address2 inverse P
8/9/2019 Hibernate (1) notes
66/691
=rder table
man9to9one: 4e would like to maintain the tables for multiple
employees we would like to have departments and there are
departments with out employees to achieve we use manyCtoCone
relationship.
Emp
Dept
one9to9one relationship:
4e would like to maintain oneCtoCone relationship
between team and captain tables. &he followin are two takes which we
are usin to achieve this.
&eam
"aptain
Note: 4hen we create the above two tables and establish the
relationships and enerate hbm 3les and 7=0= classes IDE as unC
necessarily created oneCtoCmany relationship this is because of addin a
forein key relationship between captain and team table.
1. "reate two tables team and captain with only primary key do not
add the forein in the beinnin this is because if we had a forein
key IDE will enerate oneCtoCmany relationship.'. 8enerate hbm 3les and 7=0= classes.
Eno-pk name
Did-pk
&id-pk name
location
&id-pk -pk
"name
8/9/2019 Hibernate (1) notes
67/691
). 4e have to add oneCtoCone relationship between team and captain
by usin properties
UhibernateCmappinM
Uclass . . . . M
. . . . . . . . .
UoneCtoCone name P captain2 class P info.inetsolv.captain2
cascade P all2M
UBoneCtoConeM
UBclassMUBhibernateCmappinM BBteam.hbm.5ml
#imilar to team 7=0= class and hbm 3le! develop captain java and
captain.hbm.5ml
Develop the hibernate application to store data in to data base server.
public class #tore&eamDetailsR
public static void main-#trinVW arsR
#ession hsession P Hibernate#[email protected]#ession-N&ransaction t5 P hsession.bein&ransactions-N
&eam t P new &eam-N
t.set&id-tidN
t.set*ame-team*ameN
t.set?ocation-locationN
"aptain c P new "aptain-N
c.set&id-tidN
c.set*ame-captainN
c.set&eam-tN
t.set"aption-cN
hsession.save-cN
t5.commit-N
Hibenate#[email protected]#ession-N
S
8/9/2019 Hibernate (1) notes
68/691
S
man9to9man:
4e would like to implement manyCtoCmany relationship bBw student
and course tables.
BBstudent BBcourse
BBstudentCcourse
&o specify the manyCtoCmany relationship bBw the tables we have to
provide the followin con3uration in hbm 3les.
Uset name P #tudent"ourses2 table P #tudentO"ourse2 "as"ode P
all2 inverse P true2MUkey column P #id2BM
UmanyCtoCmany column P cid2 class P info.inetsolv.course2BM
UBsetM BBstudent.hbm.5ml
&he followin is the java code to store data in the data base server.
public class #toreDataR
public static void main-#trin arsVWR
#ession hession P Hibernate#[email protected]#ession