SlideShare a Scribd company logo
Hibernate
For Evaluation Only.
Copyright (c) by Foxit Software Company, 2004 - 2007
Edited by Foxit PDF Editor
.-. -. pp.pp.--p.- ~ ... -. . . . ~ . - ..
. -
1 Hibernate-Introduction Mr.Sek11arReddy, - - -.
x.
Q) Where actually java is used?
Q Java is used to develop the enterprise applications
Q Enterprise means business organization
* Business organization provides servic2s
!
1 Q) What is Enterprise Application?
* Computerizing business services , .
1 Architecture of Enterprise Application
- . -
I
Controller Layer
I
Client Layer
-. Presentation II
I 1
Layer I
+ . a < * . : " - J :I--..- - _ "
I
1 Client Layer:
I
i 3 It is browser software.
1 Controller Layer:
1 P Receiving user request from client (calling request)
I > Capturing the user provided data
P Validating the user input
1 Calls the business method to get business services and get processed data
> Keep the processed data in memory(request/session/application scope)
I > Finally forwarding the request t o VIEW.
i
'~
IVote: should not write business-Logic/Data-Access-Logic in the Controller Layer. Because that is not reusable
Presentation Layer:
-
I P Receive the control from Controller Layer
/ P Generate the output by taking the data from memory(request/session/application scope), which is
stored by controller layer
P Generated output will be given t o web-server, which intern return present the output to browser
Business/Service Layer:
1I
Naresh i Technologies, Opp. Satyam Theatre, Anleerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 . 2000 Certified CompanyL-- - -.------ ---..--- -. -- -- - -.- -- - .--- -----.- -
Page 1
http://javabynataraj.blogspot.com 2
. , -.-- . . . - - - L--.-. i
--
O Receiving request from Controller Layer
1
P Contacting the Data Access Layer to get the database data
3 Implementing the business logic
3 Return the control/processed-data to Controller Layer
PersistentIData-Access Laver:
i Receiving the request from business Layer
I P Contacting database to get the database data
O Return the accessed data to business Layer
I
Data Laver:
1 > It is a database.
- ' Q) What are the different logics available in Enterprise Application? I
I Presentation Logic: Logic used to present the output/input. I
I
Application/Controlling Logic: Logic used t o control the flow of application. II-
1
/
Business Logic: Programmatical implementation of business rules is nothing but business logic. jI
Data Access Logic: Logic used t o contact the Database.
-
I
Q) What are the Sun Microsystems technologies and frameworks in enterprise application development?
Controller Layer
'IServlets
I / JSF
. ' I
Presentation Layer
JSP
Business Layer
t
EJB2 session beans
EJB3 session beans
WIDB(Message Driven
Beans)
' WEB-SERVICES
Data Access Layer
JDBC
Ejb2 entity beans
Ejb3 entitys[JPA ] (java
persistence API)
I Q) What are the non-Sun Microsystems technologies and frameworks in enterprise application
1 development?
1 1 Controller Layer
struts
Spring Web MVC
' I Wicket--
Tapestry
'I Flash
I I 1 ,
1 Objective of Hibernate: Developing Data access layer of an Enterprise application
1
I Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
II
Presentation Layer
HTML
Velocity
Freemarker
Flex
~ u s i n e kLa-yer
Spring AOP
Spring JEE
WEB-SERVICES
L--.
An IS0 9001:2000 Certified Company-..- -- --..-.-- --- - -- -. .--
Page 2 -
1
Data Access Layer
Hibernate
lbatis
Toplink
JDO
Spring DAO
Spring ORM
http://javabynataraj.blogspot.com 3
, Hibernate-Introduction
'
Q) What is persistence in a java based enterprise application?
!
I > The process of storing enterprise data in to relational database is Iknown as persistence
Q) What is the traditional style of achieving persistence in java based enterprise application?
I
> Sending SQL statements t o the Database using JDBC API
I
I
I
' Q.) What are the iimitations of the traditional approach?
I
'i Application portability to the Database is lost (Vendor lock: diff SQL statement for the db's)
1
3 Mismatches between Object oriented data representation and relat~onaldata representation are not
I
I properly addressed
II
3 Requires the extensive knowledge of DB
I P Manual operations on Resultset
I
7
I I
v For every problem while commun~catingwith the database (us~ngJDBC), it throws same
I
-
I
exception(java.sql.SQLException). As SQLException is checked exception, so we must write code in try- ;I
catch block or throws has to be specified. ,
I
I
I
> Need to implement caching manually iI
I
3 In the Enterprise applications, the data flow with in an application from class to class will be in the 1
form of objects, but while storing data finally in a database using JDBC then that object will be I
converted into text. Because JDBC doesn't transfer objects directly. I
'I
1 4.)what is an alternative for traditional approach?
!
/ > ORM (Object Relational mapping)
I > It is technique of mapping objected oriented data to that of relational data
> Through ORM technique persistence services (database) are provided to business layer in pure object
oriented manner by overcoming all limitations of the traditional approach II
Q.) What is Hibernate?
& Hibernate is an ORM implementation
> Hibernate is an Open source
i
!
b Hibernate is a framework
I > Hibernate invented by Gavin King. He also invented JBoss server and JPA
-
Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An I S 0 9001 :2000 Certified Company- -- I
Page 3
http://javabynataraj.blogspot.com 4
~ ~ ~ ~ ~~ ~. ~-~ . ~ ~ ~~ .~~~ .
Hibernate-Introduction -----. ---._-_.. "..._._..._Ul---
Mr.SekharReddy..-.
- ,,?--,.->>"<
3 Hibernate is a non-invasive framework, means it won't forces the programmers to extend/implement
arly class/interface, and in hibernate we have all POJO classes so its light weight
k Hibernate can run with or without server, I mean it will suitable for all types of applications (desktop
or web applications)
Q.) What is a framework?
A frameworl<is reusable semi finished application that can be customized to develop a specific
application.
Q.)What are the features of hibernate?
1
9 Hibernate persists java objects into database (Instead of primitives)
9 It provides Database services in Database vendor independent Manner, so that java applications
II become portable across the multiple databases
I
i 9 Hibernate generates efficient queries for java application to communicate with Database i
I ,
9 It provides fine-grained exception handling mechanism. In hibernate we only have Un-checked
I exceptions, so no need to write try, catch, or no need to write throws (In hibernate we have
.-
the translator which converts checked t o Un-checked)
1 3 it supports synchronization between in-memory java objects and relational records
I
> Hibernate provides implicit connection pooling mechanism !
I j
Hibernate supports Inheritance, Associations, Collections
I 3 Hibernate supports a special query language(HQL) which is Database vendor independent
1 9 Hibernate has capability t o generate primary keys automatically while we are storing the records into /
database i
1 > Hibernate addresses the mismatches between java and database
11 > Hibernate provides automatic change detection I
I
I
9 Hibernate often reduces the amount of code needed t o be written, so it lrnproves the productivity II
i
> Database objects (tables, views, procedures, cursors, functions ...etc) name changes will not affect
I
I
I hibernate code i
I > Supports over 30 dialects
Hibernate provides caching mechanism for efficient data retrieval
I- - > Lazy loading concept is also included in hibernate so you can easily load objects on start up time
1 > Getting pagination in hibernate is quite simple.
( > Hibernate Supports automatic versioning of rows i
I
I
I
Nareshi Technologies,Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i
An IS0 9001 :2000 Certified Company I
1 - - -. ..--. - -. I
Page 4http://javabynataraj.blogspot.com 5
Hibernate-Introduction- --- -- McSekharReddy-.-
I
- -
i
i 3 Hibernate provides transactional capabilities that can work with both stand-alone or java Transaction 1I
1 API (JTA)imple~nentations...etc . .
, II i Hibernate supports annotations, apart from XML
I
I I
, Q.)What are the disadvantages of hibernate? 1II 3 Since hibernate generates lots of SQL statements at runtime so it is slower than pure JDBC
i i. Hibernate is not much flexible in case of composite mapping. This is not disadvantage since
1 understanding of conlposite mapping is complex
/ P Hibernate does not support some type of queries which are supported by JDBC
1 9 Boilerplate code issue, actually we need to write same code in several files in the same application,
I
',
but spring eliminated this I
I
1
1 HibernateArchitecture
1
java application
nAL'
Hibernate API
+r----
I--- Hilreinale Engin e .- configuration file

,I D E C
'./
Data base
1
Java Application makes use of hibernate API methods calls to inform the persistent needs t o I-,hibernate. Then Hibernate engine generate .lDBC code that corresponds t o the underlying DB by using 1l-
mapping file and configuration file information. I
I
I I r. We can also find the architecture diagrams as follows ...
i I
i Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
1( 1
L.- __ - __--
An IS0 9001 : 2000 Certified Company I
.--- .- - -
Page 5http://javabynataraj.blogspot.com 6
. . . . . . . . . . . . .-. . . . . . . .
JTA J N D l
. ~
f
...r...*.-...... &..>**..&..."..,."*"? ... *..-.-...'*..." -.................
I
I -- I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i
An IS0 9001 :2000 Certified Com~anv I
Page 6http://javabynataraj.blogspot.com 7
2 .
/ 3 . < c l a s s name="Entlty c l a s s namev t a b l e = " t a b l e name I n d a t & a s e l ' >
1 4 .
< l d name="ld v a r l a b l e name" column="prlmary column name l n d a t a b a s e " />
1 5 . < p r o p e r t y name="variablel name1' column="column name l n d a t a b a s e " />
1 6 . < p r o p e r t y name=I1varlable2 name" column="column name l n d a t a b a s e " />
' 7 . < / c l a s s >
I 8 .
, 9 . </hibernate-rnapplng>
Syntax Of Mapping Annotations:
1. @ E n t i t y
2 . @Table(name= " t a b l e name i n d a t a b a s e " )
3 . p u b l i c class EntityName {
4 . @ Id
5 . @Column(name= "primary column name i n d a t a b a s e " )
6 . p r i v a t e i n t idVariableName;
7 .
8 . @Column(name = "column name i n d a t a b a s e ")
9 . p r i v a t e S t r i n g variableName1;
1 0 . @Column(nams= "column name i n d a t a b a s e ")
11. p r i v a t e S t r i n g variableName2;
1 2 . / / setters & g e t t e r s
13. 1
Q.) What is hibernate configuration file?
i It is an XML file in which database connection details (username, password, url, driver class name) and ,
Hibernate Properties(dialect, show-sql, second-level-cache ...etc) and Mapping file name(s) are t
specified to the hibernate
I > Hibernate uses this file to establish connection to the particular database server
I i
1 Z Standard for this file is <hibernate.cfg.xml>
3 We must create one configuration file for each database we are going t o use, suppose if we want to 1
ij
connect w ~ t h2 databases, like Oracle, MySql, then we must create 2 configuration files.
I
No. of databases we are using = That many number of configuration files I
I
I > We can write this configuration in 2 ways...
o XML file
o Properties file(o1d style)
( > We don't have annotations t o write configuration details. Actually in hibernate l.x, 2.x we defined this j., 
1 configuration by using .properties file, but from 3.x XML came into picture. XNlL files are
I
I always recommended t o use.
Syntax Of Configuration xml:
1. < h i b e r n a t e - c o n f i g u r a t i o n >
2 . < s e s s i o n - f a c t o r y >
3.
4 . < ! - - R e l a t e d t o t h e c o n n e c t i o n START -->
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
- ~- -
An IS0 9001 :2000 Certified Company
~Tge8-http://javabynataraj.blogspot.com 8
I Q.) What is hibernate mappingfile?
' 3 In this f ~ l ehibernate application developer specify the mapping from entity class name to table name i
1 and entity properties names to table column names. i.e. mapping object oriented data to relational
data is done in this f ~ l e I
i Z Standard name for this file is <domain-object-name.hbm.xml> I
I
I
r In general, for each domain object we create one mapping file
Number of Entity classes = that many number of mapping xmls
I Z Mapping can be done using annotations also. If we use annotations for mapping then we no need to I
write mapping file.
I
Z From hibernate 3.x version on wards it provides support for annotation, So mapping can be done in
two ways
o XML
o Annotations
Syntax Of Mapping xml:
1 1. <hibernate-napping>
i
I Nareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001:2000 Certified Company
http://javabynataraj.blogspot.com 9
5. <property name="connection.driver~~1a~s'~>DriverClass Name </property>
6 . <property name="connection.url">URL </property>
7 . <property name="connection.user">user </property>
8 . <property name="connection.password~l>pa~~~~rd</property~
9. < ! - - Related to the connection END -->
10.
11. < ! - - Related to hibernate properties START -->
1 2 . <property name="show-sqll'>true/false</property>
1 3 . <property name="dialettt>Databasedialet class</property>
14 . <property name="hbm2ddl.auto">create/update or what ever</property>
15. < ! - - Related to hibernate properties END-->
16.
17. < ! - - Related to mapping START-->
1 8 . <mapping resource="hbm file 1 name .xml" / >
19. <mapping resource="hbm file 2 name .xml" / >
20. < ! - - Related to the mapping END -->
21.
22 . </session-factory>
23 . </hibernate-configuration>
I
' Q.) What are the Simple Hibernate Application Requirements?
I -.
Setting hibernate environment
I I
I
1 1 Entity class
2. Mappingfile(Requiredif you are not using annotations)
i 3. Configuration file
1 i ;To work with hibernate framework we need to add .jar(s) files provided by that framework to '
I
I j our java application.
4. DAO class (Wherewe write our logic to work with database)
( 1 i No framework-is installable software, it means we doesn't contain any setup.exe
I 'i When we download any framework, we will get a 'zip' file and we need to unzip it, to get the required 1.i
jar files, actually all frameworks will follow same common principles like... 1
j
!
o Framework will be in the form of a-setof jar files, where one jar file acts as main (We can call !
this file as core) and remaining will acts as dependent jar files.
1
I o Each Framework contain at least one configuration xml file, but multiple configuration files also
iallowed.
> We can download hibernate jar files from the following links. Based on requirement we can download
the corresponding version.
o For version 2.x (http://sourceforge.net/projects/hibernate/files/hibernate2/)
o For version 3.x (http://sourceforge.net/proiects/hibernate/f1les/hibernate3/)
o For version 4.x (http://sourceforge.net/projects/hibernate/f1Ies/hibernate4/)
> While dowr~loadingselect .zip file for windows environment, select .tar flle for unix environment. 1
j
Naresh iTechnologies,Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001:2000 CertifiedCompany
1:I
- ---
Page 9
1http://javabynataraj.blogspot.com 10
-- Hibernate-Introduction
After downloading the zip file, unzip it and we can find the required jars in the extracted folder. If we consider
4.x version, we need the following jars to work with hibernate application.
NOTE:Along with the hibernate jars we must include one more jar file, which is nothing but related to our database, this
, is depending on your database. For example, if we are working with Oracle we need to add ojdbc6.jar.
4.) What are the Steps t o develop hibernate applications?-
1 ' Step 1: Develop persistent/domain/entity class for each table of the relational model
-
Step 2: For each entity develop a mapping file
i Step 3: Develop the configuration file
I
Step 4: Add hibernate framework jar files in the classpath
1
/ Step 5: Make use of hibernate API and perform persistent operations
4.) H o w t o Make use o f hibernate API t o perform persistent'operations?
I STEP1: Create Configuration object
Configuration configuration = new Configuration();
STEP2: Read configuration f ~ l ealong with mapping files using configure() rnethod of Configuration Object
I
configuration.configure();
1 S'rEP3: Build a SessionFactory from Configuration
I
SessionFactory factory = configuration.bhildSessionFactory();
!-STEP4: Get Session from SessionFactory object
Session session = factory.openSession();
I STEP5: Perform persistence operations
I
I
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified Company
- -- --
Page 10-http://javabynataraj.blogspot.com 11
Hibernate-Introduction
The Session interface provides methods to perforni CRUD (Create Read Update Delete) operations o n i,..-
I the instances of mapped entity classes. Perform transactions if require while performing DML: :I
operations. Session interface methods are...
I
L; S s;,0 1-1 2:a:..'*i :3 : - l!l.:.el-tincl okjelzt .8' intl:~database. ! :-
. .
ses$;it:~n 1.19date1:s:- LJ:.~.cl~!it-~ciobject ' sit1 the ~:latabase I
, STEP6: Close the session
I Final .flow will be...
Sa:ssiul-1
TI-ansaction
Close Statet?lents
~areshi Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666, 23734842
An I S 0 9001 :2000 Certified Company-- . .
Page 11http://javabynataraj.blogspot.com 12
Hibernate-CRUD Application- By Mr. SeltharRedcly--..
- . ' - A
4.) Develop Hibernate application, i n which w e can perform account creation, retrieve, update and delete?
SQL Script
CREATE TABLE ACCOLIkIT (
ACCNO NUMBER (5) IUOT NULL,
NAME VARCHAR2 (20) NOT NULL,
BAL NUMBER(8,2) NOT NULL,
CREATION-DT DATE NOT NULL,
PRIMARY KEY ( ACCNO )
1
i ACCOUNT TABLE
E::-'..L CREAT IOII-DT
fiP541.07J ':74>:7illiJ . -..- .
! 91:1U02 yellari.diis; E:i;5d$.69 5;'15;21:112
gDlli13 clierr-,! - -ac(-iS?.?6 5,,'2!2l:l12
I
I
hibernate.cfg.xml
1 1. <?xml version='l.O1 encoding='UTF-8'?>
2 . <!DOCTYPE hibernate-configuration PUBLIC
I 3.
"-//Hibernate/Hibernate Configuration DTD 3.0//ENM
4 . "http:/>hibernate.sourceforge.net/hibernate-configuration-3.0.dtdIT>
--- -- I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
I
I
An IS0 9001 :2000 Certified Company
---- -
p a s -http://javabynataraj.blogspot.com 13
, . - ~ . .- -~ ~ - .. . .. - - ~ ~.~ ~ ~~ ~ . . .~~ I -
: Hibernate-CRUD--Application.... -. ..-. ..
. . ------. - ,-&c3 . "< .
By Mr. SekharReddy -;-- --.-...... . -..--.. .-----.--.-. ---.yr*r- -.,..YLTu_,- --- .
I .%
,.:
j 1 4 . < / p r o p e r t y >
! 15. ,,./ :, .,.- ., . . ~" -. .. ,.
. - y ,;...!-:-- -.-.!!~;.c:ion. u s e r n a m e " > s y s t i : n ~ < : p r o p ~ r ~ ~ - >
j 1 6 . <propert;. ::!I:!?-" ::ci!!.!?c:?.on. passiiord">tiqer<ipropert;.:-
1 1 7 . <prop?rt:;: n :;:I.-2-"<::.::!?i:?ction.d r i v e r-c l a s s ">
j 18. G : ?z.:.e.:.;:::. : ! r i v e r . O r a c l s D r i ~ r e ~
I 1 9 . ',i ~ J L ~ . , , ~ :i;;
; 2 0 . - .>,%73, - ;-. . - - -. t c
, - . - - . .. : .!iection.pool s i z e n > l5.., i-,rpei:t;::-
1 2 1 . ;Proper ::..,. ,; -..,..= "::.:I::.: -. s c l l " > t r u e < / p r o p e r t . -
2 2 . < ,-,=.-- .. ,, -;,. -:!' .-,. ..,?-I,-! 12:. .. - '. . . . . . ... .. .. ...< . autoU>update</pr-i>;..sr~;:;:,
i 2 3 . <propert,- r~,-.;-e="us.=--s q l - c o r n m e n t s " > t r ~ e < / p r ~ ~ ~ p e r t ~ . ~ >
1 2 4 . <propert;- l > , : : > ~ = ~ !~..-.n-.tI:...-. -sqll'>true</proper-c;.:.
i 2 5 . <~nappLngre~~~ur~:~="c~~m/sekharit/hibsrnate/mappitig/Ar-cc~ur:t .
1 2 6 . </session-factor;-:.
1 27.
I
i 28. </hibernate-configura:~311:.
j 2 9 .
I
j SessionUtil.iava
1, package corn.sekharit.hibernate.ur;il;
1 2.
3. import org.hibernate.Session;
1 4. import org.hibernate.cfg.Configuration;
1 5.
1 6. public class SessionUtil {
1 7.
1 8. private static final ThreadLocaI<Session>threadLocaI = new ThreadLocaI<Session>();
I
9. private static org.hibernate.SessionFactory sessionFactory;
! 10.
,
. 
,
11. static { i
j 12. try { . .
sessionFactory = new Configuration().configure( 1-
I ::: "com/sekharit/hibernate/config/hibernate.cfg.xmI").buildSessionFactory(); - .1. .
} catch (Exception e) {
1 iii e.printStackTrace(); Ir
1
18, }
1j
1 19.
1 20. private Sessionutilo { I
21. } I
1 22. I
23. public static Session getThreadLocalSession() {
24. Session session = (Session)threadLocal.get();
25.
II
26. if (session == null) {
27. session = sessionFactory.openSession();
j_11
28. threadLocaI.set(session); !
29. } !
30.
! :;: }
. return session; 1:,
I
1 33. ?I
I 34.
public static void closeThreadLocaISession() { ! !
I 'I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I !,
! An I S 0 9001 : 2000 Certified Company I
Page 2http://javabynataraj.blogspot.com 14
-~-- -.- .- - - . ~ - ~~~. . - -- --- -
Hibernate-CRUD Application By Mr. ~ e l t l ~ a r ~ e d d ~
Session session = (Session)threadLocal.get();
tlireadLocal.set(nulI);
if (session != null) {
session.close();
1
1
public static Session getsession() (
return ses~ionFactory.openSession();
1
public stat~cvoid closeSession(Sessionsession) {
if (session != null) {
session.close();
1
1
--
, Account.java
I 1. package com.sekharit.hibernate.bean;
- 2.
/ 3. import java.ut~l.Date;
4.
1 5. public class Account {
6. private long accno;
1 7. private Str~ngname;
8. private double balance;
I 9.
private Date creat~onDate;
10.
, 11. public long getAccno() {
return accno;
1
public void setAccno(long accno) {
this.accno = accno;
1
public String getName() {
return name;
1
public void setName(String name) {
24. this.narne = name;
I 25. )
26.
1 27, public double getBalance() {
I
28. return balance;
I 29. 1
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
An IS0 9001 :2000 Certified Company
I
page~---'http://javabynataraj.blogspot.com 15
[--?
-- . .- - - - - - . . -- .-- - .- ~ ..- . ~~ , -.. -
I Hibernate-CRUD Application
! --
- --- --- -... .. . -. . .--... .-.yl.S..--
By Mr. ~ e k h a r ~ e d d ~- -
- - ~ .< ,.. ,----.U
.-
1 30.
31. public void serBalance(double balance) {
1 32. this.balance = bala~ce;
! 33. 1
35. public Date getCreationDate0 {
return creationDate;
37. }
I 38.
1 39. public void setCreationDate(Date creationDate) {
40. this.cr?ationDate = creationDate;
41. }
1 42.
43. @Override
1 44. public String tostring() {
1 45. return "Account [accno='! t accno + ",balance=" + balance
46. + ", creationDate=" + creationDate + ",name=" + name + "I";
47. }
1 48. I
Account. hbm.xml
1. <?xml version="l.O" encoding="UTF-8"?>
2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.O//ENU
/ 3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
1 4. <hibernate-mapping schema="SYSTEM" >
1 5. <class name="com.sekharit.hibernate.bean.Account"table="ACCOUNT">
<id name="accno" type="longU>
<column name="ACCNOUlength="SUnot-null="true" ></column>
</id>
<property name="nameUtype="stringM >
10. <column name="IUAMEUlength="2OVnot-null="trueV></column>
11. </property>
12. <property name="balanceUtype="doubleU >
13. <column name="BALNprecision="8" scale="2" not-null="trueN></column?
14. </property>
15. <property name="creationDate" type="dateM>
16. <column name="CREATION-DT" not-nllll="true" ></column>
17. </property>
18. </class>
19. </hibernate-mapping>
AccountDAO.iava
1. package com.sekharit.hibernate.da0;
,2.
3. import 0rg.hibernate.HibernateException;
4. import org.hibernate.Session;
5. import 0rg.hibernate.Transaction;
1 ::import com.sekharit.hibernate.bean.Account;
1 8. import com.sekharit hibernate.util.5essionUtil;
llaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
--- An I S 0 9001 :2000 Certified Company
---.- --- -
Page 4http://javabynataraj.blogspot.com 16
- - Hi..-bernate-CRUD Application. By Mr. SeltharReddywi.e-ii-ii-l---
9.
10. pcrbl~cclass AccountDAO {
3 1. (~ubllcAccount get(long accno) {
12.
13. Sess1011session = null;
, 14. Account account = null;
15. try {
I 16. session = SessionUtil.getSess~on();
I 17. account = (Account) session.get(Account.class, accno);
, 18. } catch (HibernateException e) {
I 19. e.printStackTrace();
20. } f~nally{
1 21. SessionUtil.closeSession(session);
22. 1
1 23.
24. return account;
j 25. }
26.
27. publ~cv o ~ d~nsert(Accountaccount) {
i28.
1 29. Session session = null;
I 30. try {
731. session = SessionUtll.getSession();
I 32. session.getTransaction().begin();
33. session.save(account);
1 34. session.getTransaction().cornm~t();
35. } catch (HibernateException e) {
1 36. session.getTransaction().rolIback();
37. e printStackTrace0;
1 38. } f~nally{
39. SessionUtil.cl~seSession(session);
1 40. }
I 41. }
42.
I 43. publ~cvoid update(Acc0unt account) {
44. Session session = null;
I 45. try {
46. session = SessionUtil.getSession();
1 47. sess~on.getTransact~on().beg~n();
48. session.update(account);
1 49. session.getTransaction().comrnit();
50. } catch (HibernateException e) {
( 51. session.getTransaction().rollback();
-- 52. e.printStackTrace();
I 53.
} f~nally{
54. SessionUtil.closeSession(session);
55. 1
I 56. }
57.
1 58. public void delete(long accno) {
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
--
An IS0 9001 :2000 Certified Company
- -
PagT5-http://javabynataraj.blogspot.com 17
-.-- -.-- - - - -. - -- .-- - . -. .- --- -. -
Hibernate-CRUD Application B Mr.Sel<harRecldy--
Session session = null;
Tramaction transaction = null;
try I
session = SessionUtil.getSession();
transaction = session.beginTransaction();
Account account = (Account) session.get(Account.class, accno);
session.delete(account);
transaction.commit();
} catch (HibernateExceptione) {
transaction.rolIback();
e.printStackTrace();
} finally {
SessionUtil.closeSession(session);
1
i AccountService.iava
1. package com.seltharit.hibernate.service;
I 3. import java.util.Date;
5. import corn.sekharit.hibernate.bean.Account;
I 6. import corn.sel~harit.hibernate.dao.AccountDA0;
1 7.
/ 8. public class Accountservice {
9. public static void main(String[] args) { -
I
10. AccountDAO dao = new AccountDAO();
11.
12. // Retrieve Account
13. Account rAccount = dao.get(90001);
14. Svstern.out,println("Account details ....");
Systern.out.println("Accno : " + rAccount.getAccno());
1 ::: System.out.println("Name : " + rAccount.getName());
17. System.out.println("8alance : " + rAccount.getBalance());
18. Systern.out.println("CreationDate: " + rAccount.getCreationDate());
1 19.
20. // Create Account
21. Account cAccount = new Account();
22. cAccount.setAccno(90005);
23. c~ccount.set~ame("sekhar");
24. cAccount.setBalance(6899);
25. cAccount.setCreationDate(new Date());
1 26. dao.insert(cAccount);
1 27. System.out.println("Account created successfully");
28.
29. // Update Account
I 30. Account uAccount = new Account();
31. uAccount.setAccno(90003);
32. uAccount.setName("sekhareddy");
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified Company
---
Page 6http://javabynataraj.blogspot.com 18
I--, Hibernate-CRUD Application--- -- ---.. . . . . . -- . . . . . .
By Mi-.Sel;ha~-Reddy
!
33. uAccount.setBalance(4500);
34. uAccount.setCreationDate(new Date());
35. dao.update(uAccount);
36. System.out.println("Account updated successfully");
37.
38. // Delete Account
39. dao.delete(90002);
40. System.out.println("Account is deleted successfully");
41.
42. }
43. }
After Execution ACCOUNT TABLE :
,-*. .?
;;.,-.c c- 1.10 Il.,li.lE E:AL CREhT 101I-UT
t I:i.:a>, ?:-eddy 69541.03 5: 29,'21:1!::
9l:ll:lOj ~e;tllll-edjj' 45i10 j!Z?jLI:l]z
!21:11:105 5el:hal- 6Sgg 529jiC112
1 Q.) Rewrite the above application, using annotations instead of mapping file?
d . . *' cctn.rtkb~arit.hih~rnatr.utiI
:.i. .: Ser-~ian!JtiI,~a~.~a
. ., .
r-:.:,.-J. JRE S y . ~ t i i i ~L i b r a y ,...;;a::,:. . ,
- -Hitxrnate 3.3 Annctation': F,t Entit!. I:;lanagel......
i , . Hitlel-nate3.3 Cnre Libraries
LI ~ i jRefer~ticedLihrariel:
080 c<clbclJ,jar
lib
3 . . ,.
1 hibernate.cfg.xml
. .
: 1. <?xml version='l.O' encoding='UTF-8'?>
1 2. <!DOCTYPE hibernate-configuration PUBLIC
3 .-- "-//Hibernate/Hibernate Configuration DTD 3.0//ENn
4. "http://hibernate.sourceforge.net/hibernate-configuration-3.O.dtd"~
I 5 .
6. <hibernate-configuration>
8. <session-factory>
9. <property.... />
............
! Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
Page Ihttp://javabynataraj.blogspot.com 19
~ . - .. -
i1 - Hibernate-CRUD Application By Mi-.Sekhal-lieddy.- -:,
--
/ -. . -.'%-*au#A&.Lcas* -*=--&= i
I
~'-,
; 23. 1
24. ' A
! 25. public void setAccno(1ong accno) {
j 26. this.accno = accno; ,,
' 27. }
1 28. I?
! 29. @Column(name= "NAME", nullable = false, length = 20) ,.
30. public String getName() {
,--..
31. return name;
32. }
! 33.
, .
I
: 34. public void setName(String name) {
1 35. this.name = name;
~.
j 36. } !
i 37. I
I 38. @Column(name= "BAL", nullable = false, precision=8, scale=2) .
I
1 39. public double getBalance() { I
) 40. return balance; 
41. } 1/
1 42. , j
I
1 43. public void set~alance(doublebalance) { I
44. this.balance = balance; -
45. } I
1 46.
., 
I x.
47. @TemporaI(TemporaIType.DATE)
I !
I 48. @Column(name= "CREATION-DT", nullable = faise) ,. 
 ,
1 49. public Date getSreationDate() {
i 50. return creationDate; 1I .
51. } i-
52. 1,h :.
53. public void setCreationDate(Date creationDate).{ ,I* .
54;
!
this.creation[>ate = creationDate; 1.-
55. }
56.
I
i
1 57. @Override
1
58. public String tostring() {
1
59. return "Account [accno=" t accno + ",balance=" + balance 1,
1 60. t ",creationDate=" + creationDate + ",name=" + name + "I";
61. }
l~
i
1 62.
, 63. 1
Account.hbm.xml
I1:
---NOT REQUIRED--- -
I,
AccountDAO.java !
I ,
---Same As Above--- I -
i
I
AccountService.iava I!
---Same As Above--- 1 ' -
/ I
/ r
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 i
An I S 0 9001 :2000 Certified Company II 
-- _ _ _ _ 1
Page 9http://javabynataraj.blogspot.com 20
-.- -- - - -. -- -- --- - -- -- -- - ---- - --- - - - - ----
H ibernate-CRUD Application Bv MI-.~ e l t h a r ~ e c l d v -
Hibernate - The type Annotationconfiguration is deprecated
I
I Problem
I
Working with Hibernate 3.6, noticed the previous "org.hibernate.cfg.Annotat~onConf~gu~-at~on",1s marked as
"deprecated".
Code snippets ...
org.hibernate.cfg.AnnotationConfiguration;
private static SessionFactory buildSessionFactory() {
try 1
return new AnnotationConfiguration().configure().buildSessionFactory();
1 } catch (Throwableex) {
The code is still working, just keep displaying the deprecated warning message, is there any replacement for
I "AnnotationConfiguration" ?
I
I
!
-
I
-
i Solution
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionlnlnitializerError(ex);
1
. I
Q In Hibernate 3.6, "org.hibernate.cfg AnnotationConfigurat~on"is deprecated, and all its functiona!~tyhas been
! moved to "org.hibernate.cfg.Conf~gurat~on".
I 4 SO, you can safely replace your "AnnotationConfiguration" with "Configuration1' class.
I Code s n i ~ ~ e t s...
import org.hibernate.cfg.Configuration;
! /I...
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionlnlnitializerError(ex);
1
I
1
I
I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
Page 10
private static SessionFactory buildSessionFactory(){
try 1
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
http://javabynataraj.blogspot.com 21
-- .- - - - - -- - - - _-- _ __ .,,
Hibernate-CRUD Application-.-___a
By Mr.SeltharRedciy- -- ---.-----.
-'-4- I
A
Account" />
SessionUtil.java
. .
1. package com.sekharit.hibernate.uti1; I
," -
' 2, import org.hibernate.Session;
3. import org.hibernate.cfg.AnnotationConfiguration; ,i.
4. public class SessionUtil { % .
I
5. I
,'
6. private static final ThreadLocal<Session> threadLocal = new ThreadLocaI<Session>();
7. private static org.hibernate.SessionFactory sessionFactory;
8.
, I
9. static {
I' 10. try {
! 11. sessionFactory = new AnnoationConfiguration().configure(
: 12. "com/sekharit/hibernate/config/hibernate.cfg.xmI").buildSessionFactory(); -:I, 13. } catch (Exception e) {
I
14. e.printStackTrace(); ,"
15. } -
1 16. } I
I
, 
1 17. ...........................
1 18. ........................... r
Account.iava
1. package com.sekharit.hibernate.bean;
2.
3. import-java.util.Date;
4.
5. import javax.persistence.Column;
I 6. import javax.persistence.Entity;
1 7. importjavax.persistence.ld;
I 8. importjavau.persistence.Table;
1 9. import javax.persistence.Tempora1;
' 10. import javax.persistence.TemporalType;
i 11. @Entity
1 12. @Table(name="ACCOUIVT") .
1 13. public class Account {
1 14. private long accno;
15. private String name;
16. private double balance;
17. private Date creationDate;
18.
' 1 9 . @Id
20. @Column(name= "ACCNO", nullable =true, length=5)
21. public long getAccno() {
122. return accno;
Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company. . . . . . . . . .- . . . . . . . . . . . . . . . . . . . - .... - -..- .-- --.
~a ge8.'http://javabynataraj.blogspot.com 22
' ' Hibernate-Arcl~itect~~ralElements
, Q.) Explain more about hibernate.cfg.xml (configuration file)?
I
I .
3 This xml file used to specify locations of mapping files/Entities
I > In projects we don't give the database details(ur1, username, password, driverclass) in the
I configuration file, instead of that, we give JNDl name of DatatSource.
<property name="connection.datasource"~myDataSourceIlame~/property~
I
9 Hibernate slupports default connection pooling but which will not be used in projects We use always
1 server provided connection pooling.
I I) connection.pool-size: Used to configure hibernate provided connection pooling in hibernate.cfg.xml :
I
I
I
2) show-sql: if the 'show-sql' value is true we can view all the hibernate generated queries in the
I
console.
<property name="show~sql"~true~/property~
I
-- 3) use-sql-comments :To add SQL comment t o the SQL query generated by Hibernate
I <property name=" use~sql~comments">true~/property~
I
-
1 4) format-sql : Format the SQL ql;ery, so that easy to read
<property name format-sqln>true</property>
5) hbm2ddl.auto: It has two values
I a. create or create-drop
b. update
I
a,) Create: If its value is create while running the application
!
Case 1:table does not exist
i Create new schema based on the mapping file configurations
i
Case 2: table exists
Drop the existing schema and create a new schema based on the mapping file configurations
I b.) Update: If its value is update while running the application
I Case 1:table doesn't exist
Create a new schema based on the mapping file configura.tions
I Case 2 :table exists-
i Use the existing schema
1 > If its value is 'create' while running the application hibernate will drop the old schema and it will
I
create the new schema. (Based on HBlVl file)
I NareshiTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
-. ---
An IS0 9001 :2000 Certified Company-------
P a g e 1http://javabynataraj.blogspot.com 23
I
3 If its value is 'update', hibernate will check for schema existence. If schema doesn't exist it will
I I
create the new schema. If the schema already exists it uses the existing schema for persistence
operations.
Q.) What do you know about dialect in Hibernate?
P Dialect class is a simple java class, which contains mapping betweerr java language data type and
database data type. i
/ P Dialect class contains queries format for predefined hibernate methods I
2 Hibernate generates queries for the specific database based on the Dialect class. If you want t o shift 1
from one database to another just change the Dialect class name in hibernate.cfg.xml file. 1
I
1 9 All Dialect classes must extend 'Dialect' (abstract) class
i
!
1 9 Hibernate supports almost 30 dialect classes.
9 If we want we can write our own dialect by extending Dialect class
I
I Dialect class is used convert HQL queries into database specific queries.
I I 
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1
An IS0 9001 : 2000 Certified Company I .--- - - -- -1
Page 2http://javabynataraj.blogspot.com 24
Hibernate-Arcl~itecturalElements
I
MySQL with InnoDB 1 org.hibernate.dialect.MySQL5lnnoDialect
DB2 AS1400
DB2 05390
PostgreSQL
1 MySQL
I I Oracle (any version) org.hibernate.dialect.Oracle8iDialect I
-
org.hibernate.dialect.DB2400Dialect
org.hibernate.dialect.DB2390Dialect
org.hibernate.dialect.PostgreSQLDialect
org.hibernate.dialect.MySQL5Dialect
1 Sybase
1
org.hibernate.dialect.SybaseDialect
' oracle 9i
1 1 oracle l o g
org.hibernate.dialect.Oracle9;Dialect
org.hibernate.dialect.Oracle10gDialect
1 I Microsoft SQL Server / org.hibern;te.dialect.~~~server~ialect
'/
>Sybase Anywhere
TI Microsoft SQL Server 2008 I org.hibernate.dialect.SQLServer2008Dialect
I
I
I
org.hibernate.dialect.SybaseAnywhereDialect 1 I
I I SAP DB 1 org.hibernate.dialect.SAPDBDialect ,
8 !
I I
HypersonicSQL 1 org.hibernate.dialect.HSQLDialect 1 1
I I -I
I I lngres
Mckoi SQL
-1 I
I org.hibernate.dialect.MckoiDialect
I
org. hibernate.dialect.lngresDialect
org.hibernate.dialect.ProgressDialect1 I
I
Q.) Explain more about Hibernate mapping file?
I
I
Progress
I lnterbase
FrontBase
1 / Firebird
> Each hibernate mapping file must contain only one <id> (or relevant tag <composite-id>)
> Java object identified uniquely by the <id> tag property.
org.hibernate.dialect.lnterbaseDialect 1 !
i
org.hibernate.dialect.FrontbaseDialect
org.hibernate.dialect.FirebirdDialect
..A
I > <id> tag property corresponding column can be primary key or non-primary key in the database
org.hibernate.dialect.PointbaseDialectPointbase
I
I
> In mapping file class names and property names are case sensitive. But Table names and column
I
I
I
names are not case sensitive. !
1
1
I
Nareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 !
An IS0 9001 : 2000 Certified Company-- PTe- 2-...-
http://javabynataraj.blogspot.com 25
, ~
~~ . - ~ ~ . .~ ~ . ~ ~ ' ,
Hibernate-Architectul-a1Elementsj -~. . . . . . . . -- Mr.SekharRecidy-La,D . - .
i - 
I 
Ii P When the property name and column name both are same we no need t o give 'column' attribute :,-
r When the Pers~stentclass name and table name both are same we no need to give 'table' attr~bute
r Generally we write one mapping f ~ l eper one domain object. But it allows writing multiple objects -
mapping information within the same mapping file. Per each class mapping we need to write one
<class> tag.
I
r Databases have different ways to organize its tables. Some database places all tables in a different
"schemas", some database places all tables in a different "catalogs". If we want we can specify this in
<class> tag of the mapping file
i 9 In mapping file we write fully qualified name of the entity class in "name" attribute of <class> tag.
Instead of that we can write package name separately using "package" attribute of <hibernate-
mapping> tag
P In the mapping file we no need t o map all the properties of the entity and all the columns of table. As
per our requirement we configure required properties of the entity and columns of the table
1 Q.) Explain about annotations which are used in our application t o map entity t o table?
I P In our examples if we observe, we used the following annotations
II o @Column---we----
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified Company
Page 4http://javabynataraj.blogspot.com 26
~ pppp-.- ..... . .
Hibernate-AI-chitecturalElements .......................8 _nl..x&r ... -~.. , . . I
~ r . ~ e k l ~ a i - ~ e c l d y--. -
-
o @GeneratedValue
o @Temporal
/- All the above annotations we are taking from java.persistence package. Actually this paclcage is not
the part of hibernate API. This paclcage is from .IPA(Java Persistence API).
> These annotations also given by hibernate. But we don't prefer to use hibernate given annotations.
We prefer t o use .lPA annotations. Reason for this is, Hibernate is a specific API, where as ]PA is a
specification.
If we use JPA annotations we have to flexibility to change the implementation vendor without
changing application code.
i > .IPA is an APl(from SUN), its not the implementation. There are multiple implementations are there
for ]PA. Some of famous implementation of ]PA are Open.lPA, Hibernate, Toplink Essentials, Eclipselinlc
...etc.
' 4.)What is Configuration object?
> Object Oriented representation of hibernate configuration file along with mapping file is known as
-
Configuration object
- 3 By default Hibernate reads configuration file with name "hibernate.cfg.xml" which is located in1
"classes" folder
I
9 If we want t o change the file name or if we want change the location of "hibernate.cfg.xml" then we
need to pass user given configuration file name (along with path) t o "configure()" method of
1 Configuration class
1 P Configuration object Stores the configuration file data in different variables. Finally all these
variables are grouped and create one high level hibernate object called SessionFactory object.
I
P So Configuration object only meant for creating SessionFactory object
I
> If we want we can provide the configuration information programmatically, without writing
I configuration file.(But it will become Hard coding, so not advisable)
1 Programmatic configuration
I Adding mapping files to configuration object programmatically
-- Configuration cfg = new Configuration()
1 .addResource("ltem.hbm.xml")
.addResource("Bid.hbm.xml");
I
- . -
Adding Entities(anrl0tated persistent classes) t o configuration object programmatically
I
Nareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified CompanyI . . . . . . . . . . .
Page 5http://javabynataraj.blogspot.com 27
-- - - . ~. - ..-~--.. - - -.- . - - -..--- -. --. . -.
I
Iiibel-nate-AI-chitectul-a1Elements. ----- --- --- - .- -- ..---. . ,- . . . . . - ,.- . -
MI-.SekharRectciy
1- ......- ... .~ .- m.JI,X,
I
,. ,
Configuration cfg = new Configuration()
..
.addClass(org.hibernate.auction.ltem.class)
.addClass(org.hibernate.auction.Bid.class);
i
i
) To add hibernate properties to Configuration object programn~atically
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.ltem.class)
.addClass(org.hibernate.auction.Bid.class)
.setProperty('hibernate.diaIect", "org.hibernate.dialect.MySQL11~noDBDialect")
.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
.setPr~perty("hibernate.order~updates","true");
This is not the only way to pass configuration properties to Hibernate. Some alternative options include:
1. Pass an instance of java.utiI.Properties t o Configuration.setProperties().
2. Place a file named hibernate.properties in a root directory of the classpath.
3. set System properties using java -Dproperty=value.
4. Include <property> elements in hibernate.cfg.xm1 (this is discussed later).
If you want to get started quickly hibernate.properties is the easiest approach.
The org.hibernate.cfg.Configuration is intended as a startup-time object that will be discarded once -
aSessionFactory IS created.
I Q.) What is SessionFactory?
SessionFactory is an interface and SessionFactorylmpl is the implimented class
It is factory of Session objects
It is heavy weight object that has t o be created only once per application. SessionFactory object
provides lightweight Session objects.
SessionFactory is not singleton. Lets create it only once using Util/Helper class
SessionFactory is a Thread safe object.
You need one SessionFactory object per database. So if you are using multiple databases then you would have
to create multiple SessionFactory objects.
SessionFactoryis also responsiblefor second-levelcaching.
Q.) In one appl~catlon,how many SessionFactoryobjects Ican use ?
> ASessionFactory is pretty heavyweight, so, we recommend creat~ngone and caching it in a singleton type of
way. Then, you can create as many Session objects from it as you like.
Q.) Why SessionFactoryis heavy weight?
P SessionFactory encapsulates Session objects, Connections, Hibernate-properties, cashing and
mappings.
- -- - - - - - - - - - - - - -- --- - - - -- -- - - -
Naresh i Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842
--
An IS0 9001 :2000 Certified Company- -
~ a g e 6 -http://javabynataraj.blogspot.com 28
Hibernate-Architectural Elements
Q.) What do you know Session object?
Session is an interface and Sessionlmpl is implemented class, both are given in orghibernate.";
r Session object is called persistent manager for the hibernate application.
r It is a single-threaded(not-thread safe), short-lived object
> It Wraps a JDBC connection
r The Hibernate Session operates using a single JDBC connection which can be injected by the
hibernate while constructing session object.
I
> It has convenience methods to perform persistent operations.
r It is a factory for Transaction objects
r Holds a mandatory (first-level) cache of persistent objects
I
Note: After we complete the use of the Sesslon, ~thas to be closed, to release all the resources such as
associated objects and wrapped JDBC connection.
, 4.)What is Transaction ?-
-..
r Transaction used by the application to specify atomic units of work (Transaction management).
- i Using Session Object we can create Transaction object in t w o ways.
o Transaction transaction =Session.getTransaction();
o Transaction transction = session.beginTransaction();
> Transaction object is unique per session object.
> Transaction interface defines following methods to deal with transactions.
o transaction.begin() {Transaction beginning)
o transaction. commit(); { successful transaction ending )
o transactin.ro!lback(); {un successful transaction ending )
> Default auto commit value is false in Hibernate.
r Default auto commit value is true in JDBC
3 In hibernate even to execute one DML operation also we need to implement Transactions.
> Hibernate supprots
o JDBC Transaction.
o jTA Transaction.
o Spring Transaction
- Sample transaction code is as follows...
I
- 1. Session = sessionFactory.openSession();
I 2. Transaction t x = null;
3. tv {
4. tx = session.beginTransaction();
I 5. // DML operations
6. tx.commit();
I 7. ) catch(Exceptione) {
-1
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
. ..-..- - ....--..-. ..--.-- .. ...- .. --.--
An IS0 9001 : 2000 Certified Company-- --
Page 7http://javabynataraj.blogspot.com 29
11 Hibernate-Architectural Elements . , Mr.Se1tharRecldy--=A.-- -- s -
1 Q.) Why we have written SessionUtil class?
C When some common logic is repeat~ngacross the rnult~pleclasses of an application, ~tIS better to
1
move the common logic into some util class. Where ever we need that common logic we make use of
i util class. I
!
i
I
0 SessionFactory is heavy weight and it's not singleton, so we should make one SessionFactory per
1
database. i
i 0 Using Util /Helper class we read the configuration file only once and we create one SesisonFactory .
I
and we are providing fac~lityto get session object and t o close session object. I
/ Hibernate complete architecture
Read
!
!I
class
i'i.ypl.
I
configure adatabase driver in eclipse: !:
> Launch or open MyEclipse Database Explorer prospective. In the DB Browser window right click on
1 the white place and select "new " option. iL
.mEC' .-
, C'scatc A
TJses
i
Scssiorl Factor?. I 1 DAI~I~:,SC L<cr,c.i
.. -1::. -
. - v
1
I
/ O When we choose the new option, it will launch database driver dialog box. Now we need t o fill the
Creates
cation 1
/I
- -
I following options in the dialog box. I
......... _ ....
Session
/ > Select driver template as oracle(thin driver), if we are using oracle database.
3' ......
--
-.. ......... ................ ---...................-.....-.........-... - .--
Give the driver name (logical name, which is used t o refer this configuration) 1I
1
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I
1
An IS0 9001 :2000 Certified Company
Page 8
Jhttp://javabynataraj.blogspot.com 30
Hibernate-Architectural E l e i ~ ~ e i ~ t s
3 Give the connection url.
I
3 Give the username and password. I
> Click on Add Jars button, then se!ect classes.jar file !
I- Click on save password
> CIick on finish
Hibernate Reverseengineering
> Open Myeclipse database explorer prospective.
i Select the database driver which we have created and right click on it and select open connection
1i It will display a dialog box. Fill the required username and password. 1I
r Select appropriate schema where our tables are stored
> Right click on the table and select "hibernate reverse engineering"
'i The above operation will display a dialog box i n that
I
> we need t o select the "java source folder (src)"
> select the java package and click on finish
I
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
-.
An IS0 9001 :2000 Certified Company
Page 9http://javabynataraj.blogspot.com 31
; Hibernate-Persiste~~tObject Lifecycle. . ." Mr.SekharReddy -I - - - , -
1 ,,
I
Persistent Object life cycle
1 Persistent Object has three life cycle states
1. Transient state
! 2. Persistent state
I
3. Detached stateI
I (-"]new - -.-.-instance
: 'L-
Transient State
--A -- --
I Session.get()
I j Session.load() Session.save() ; Session.delete()
Session.iterate()
! Session.saveOrUpdate() i
Session.uniqueResult() Sc.ssion.persist()
arb age collection
I
1.
B Session.scroll()1 : : Session.merge()
i
f
i
1 I
: Session.evict() Session.update()1
! Session.saveOrUpdate()
i : Session.clear() i
t Session.merge() ~arbage'collection
i : Session.close()
1 Session.lock()
I j Session.replicate() ,,(. '
! /.',.
i ; :
Detached State ,
/
Persistent state
Note:
Life cycleobject description
Transient state
Object associate with session
NO
IIDetached state
I I
-
3 Object is associated with session means object reference is available to the session object
Object present in the database
YES
N0
9 Object present in the database means object identifier value is available in database primary key column (Non
identifier column values are not matter)
YES
YES
Note: We can find the different diagrams for the persistent object life cycle as follows
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
Page 1http://javabynataraj.blogspot.com 32
Hibernate-Persistent Object Lifecycle---.- --. - - -. --.-.
MI-.SekharReddy
I - I
,
.--- ,-, ;<;, 2;:
. _ ,_.A,.._..- - - r  ..--/_/- --__---- !,2;/#; I...,.
- ---_-- ,.,,-,.,,::,I!.!,;I;,~~ I'~I.IcI(;I~~ ! ? r a t . ~ ~ ~P I ~by------- I I',., ----
/~,lill,~:i;~i:l~~;)a~(!cl~,2~[l:$?::!, '-I ?PI'~~~IPI'I!
IT^^-^.. . - ..--/ .. ,I i'11 lrjl;. 31il.e~' - 1 1, 1 ,A2 .p:#:111r-:--tdL,.
.%.., I I
'-7r..'
I
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
7-4 . --_-----Ada!:ltpd from "Hlt:~prr!atp iij 4:ti:y.i' ;
-
I
/byIBallet' 4G King ,I
An IS0 9001 :2000 Certified Company 1Page 2
D~tached
http://javabynataraj.blogspot.com 33
I
.. -- .. .. -- -. --,
I Hibernate-Persistent Object Lifecycle -- ~ r . ~ e k h a r ~ e d d T -.I - I _ m _ _ < - w - S %
.. . -- ,.- i
Transient state: An object is said to be in transient state, when it is not associated with session and not present in
data base.
Example: Table
ACCOUNT
1 ACCNO / NAME / BALANCE 1
1001 kesavareddy 1500
11002 1Sekhar 2 0 0 0 1I
I
i Application code:
1. Account account = new Account();
2. account.setAccountld(1003);
3. account.setName("yellareddy");
1 4. account.set8alance(l500);
> In the above example account object is not associated with session and there is no matching record in the
ACCOUNT table. So we can say that account object is in transient state.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
--
An IS0 9001 :2000 Certified Company-- --
,
Page 3 --
http://javabynataraj.blogspot.com 34
' Hibernate-~ersistel~tObiect Lifecvcle
i
3 In this state object is non-transactional. 1.e. object is not synchronized with record. 1.e. IVlodifications done to
1
1 entity, doesn't save into database.
( Persistent state: An object is said to be in persistence state, when it is associated with session as well as object present
in database.
I
- ' Example: Table
i ACCOUNT
ACCNO ( NAME 16iiEF
kesavareddy ( 1500' ~ - y1 Sekhar
I
' Application code:
I Account account = (Account) session.get(Account.class,1002);
P In the above example account object is associated with session and there is a matching record in ACCOUNT
! table. So we car: say that account object is in persistent state.
I P In this state object is transactional. 1.e.the object is synchronized with database record.
I
P Changes made to objects in a persistent state are automatically saved to the database without invoking session
1 persistence methods
' USE CASE: Explains Persistent stateI
Session session =SessionUtil.getSession();
1 session.getTransaction()begin();
! // 'transient' state - Hibernate is NOT aware that it exists
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An I S 0 9001 :2000 Certified Company
-- -
Page 4.http://javabynataraj.blogspot.com 35
- - - -- -- - -
1 Hibernate-Pel-sistei~tObiect Lifecvcle Mr.SekharReddv 1
/ Account account = new Accoui;t();
1
! //transition t o the 'persistent' state. Hibernate is N O W
1 // aware of the object and will save it to the database
I session.save(account);
1 // modification of the object will automatically be
// saved because the object is in the 'persistent'state
account.setBalance(500);
i // commit the transaction
session.getTransaction().co~nrnit();
I USE CASE: Explains Transient state
/ Session session =SessionUtil.getSession();
sess~on.getTransaction().begin();
1 // retrieve account with id 1.account is returned in a 'persistentJstate
, Account account = (Account)session.get(Account.class, 1);
// transition to the 'transientJ state. Hibernate deletes the
// database record, and no longer manages the object
I session.delete(account);
// modification is ignored by Hibernate since it is in the 'transient' state
account.setBalance(500);
// committhe transaction
session.getTransaction().comrnit();
// notice the Java object is still alive, though deleted from the database.
// stays alive until developer sets t o null, or goes out of scope
I System.out.println(account.getBalance());
Detached state: An object is said to be in detached state, when the object is not associated with session but present in
database.
Example: Table
ACCOUNT
I ACCNO I N A M E I BALANCE 1
1001 1kesavareddy / 1 5 0 0 1
I 1002 . / Sekhar 2 0 0 0 II I J
Application code :
1. Account account = new Account();
2. account.setAccountld(1004);
3. account.setName("cherry");
IVaresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 :2000 Certified Company- .- -. --- -- - - - -.- --- --
Page 5
http://javabynataraj.blogspot.com 36
Hibernate-Persistent Object Lifecycle -- Mr.Selt11arReddy
I
L" -- ~~-~~-..----A -
4. account.setBalance(2100);
5. //Now the account object is said to be in transient state
6. session.save(account);
7. // NOLVthe account object is said to be in persistence state
. -,-
I Session
. . . . . . ......
... ..
..................
........
. .
.....> __I
iI LOU2
lOUJ -
9. // Now the account object is said to be in detached state.
account
.........
...................
......
. .. .
.,' . .,
-
I => In the above example after callingsession.close() method, account object is moved to Detached state from persistent
state. As session is garbage collected, if we try t o perform some modifications to entity object those changes will not be
/ stored into database.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company-- --
Page 6http://javabynataraj.blogspot.com 37
- ~ . .~ p-p-p-.-.----..... ~ . -~ ~.-- ..~
.. . . . ,
Hibernate-Persistent-- -. --- Object Lifecycle Mr.SeltharReddy........ . -... --__.ii_-../i
,-,
=> In this state object is non-transactional. Means object is not in sync with database. So Changes made to detached
'
objects are not saved to the database. -,
I
i USE CASE: Explains Detached state 1
I
, // retrieve account with id 1.account is returned i n a 'persistent' state
/ Account accoilnt = session.get(Account.class, 1);
i // transition to the 'detached' state. Hibernate no longer manages the object
I
i session.close();
1
I
// modification is ignored by Hibernate since it is in the
//'detached1 state, but the account still represents a row in the database
account.setBalance(500);
i // commit the transaction
session.getTransaction().commit();
1 USE CASE: Explains Detached state
/ Session session1 =SessionUtil.getSession();
i // retrieve account with id 1.account is returned in a 'persistent' state
Account account = sessionl.get(Account.class, 1);
I
i // transition t o the 'detached' state. Hibernate no longer manages the object
I Sessionl.close();
I
I
// modification is ignored by Hibernate since it is in the
//'detached1 state, but the account still represents a row in the database
/ account.setBalance(500);
// re-attach the object to an open session, returning it t o the
//'persistent1 state and allowing its changes t o be saved t o the database
Session session2 =SessionUtil.getSession();
Session2.getTransaction(). begin();
session2.update(account);
I
1 1 // commit the transaction . "
j'
Saving Changes to the Database
r3 Session methods do NOT save changes t o the database
- save();
- update();
-- delete();
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
.-
An IS0 9001 :2000 Certified Company
page-7-http://javabynataraj.blogspot.com 38
-- -. ~
-. -.~- . - . - - - .---
:- Hibernate-Persistent Object Lifecycle Mr.Selc11al-Reddy
I ..--. .-.-. i
a These methods actually SCHEDULE changes to be made to the database
Once Transaction committed, all the queries will be pushed to the database
- session.getTransaction().commit();
The Persistence Context
4 Each Session object contains one Persistentcontext. It might be containing the follow things:
' Graph of managed persistent instances
i List of SQL statements t o send to the database
i
I
' ~ l u s h i n gthe Context
,! Submits the stoied SQL statements t o the database Occurs when:
, - transaction.commit() is called
1 - session.flush() is called explicitly
1 USE CASE :Scheduled Changes
Session session =SessionUtil.getSession();
( Session.getTransaction().begin();
// 'transient' state - Hibernate is NOT aware that it exists
Account account = new Account();
//Transition t o the 'persistent' state. Hibernate is NOW
// aware o f the object and
//schedules the insert statements t o create the object in the database
session.save (account);
// modification of the object will automatically be saved scheduled
//because the object is in the 'persistent' state
// (actually alters the initial insert statement since it hasn't been sent yet)
account .setBalance(500);
I //flushes changes t o the database and commit the transaction
session.getTransaction().commit();
1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
- An IS0 9001 :2000 Certified Company
rage trhttp://javabynataraj.blogspot.com 39
---..- - - -. -- --- -.-
I H [be1nate-Session Methods Mr.SeltharReddv -
i
I
Session m e t h o d s
1 28. }
i : public void setName(String name) {
1 31. this.name = name;
1 I a m going to use the following entity to explain the session methods.
; 1, 9ackage corn.sekharit.hibernate.entity;
!
, 2.
j 3. import javax.persistence.Column;
, 4. ~lnpoitjavax.pers~stence.Entity;
I
i 5. import javax.persistence.ld;
1 6. import javax.persistence.Table;
! 7.
1 8. @Entity
9. @Table(name= "ACCOUNT")
1 10. p~tblicclass Account (
11. private int accountld;
I 12. private String name;
1 13. private double balance;
i 14.
@Column(name= "BALANCE")
public double getBalance() {
return balance;
I
,
public void setBalance(double balance) (
this.balance = balance;
1
' 15. @Id
16. @Column(name = "ACCNO")
17. public int getAccountld() (
18. return accountld;
19. }
20.
@Override
public String tostring() {
return "Account [accountld=" t accountld t ",name=" t name
t ",balance=" t balance t "I";
public void setAccountld(int accountld) (
this.accountld = accountld;
25. @Column(name= "NAME")
1 26. public String getName()(
, 27. return name;
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified Company
1: -
Page 1http://javabynataraj.blogspot.com 40
4.)What are the differences between load() and get() methods?
Hibernate Session provides two method to access object e.g. session.get() and session.load().Both looked quite similar
to each other but there are many differences between load and get method which can affect performance of our
application.
1.) Throws "org.hibernate.0bjectNotFoundException' if object is not found in cache as well as on database.
:Type hierarchy of 'org.hibernate.(3bjectNotFounilExcepti~ri':
-> As we can see the ObjectNotFoundException hierarchy, we can say this is un-checked exception..... So we no need to
write try-catch block t o handle this exception.
-
/ 2) It is lazy loading, rrieans when we call session.load(Class, identifier) method it will not return entity object, it will,
return proxy object. When we try to access the non-identifier properties from the proxy object, at that time it will hit
1
i the database and load the entity object.
i 3) As Session.load()return proxy instance, so it is not fully available in any future detached state.
I 4) Use this method if it is sure that the objects exist.
5) It is just like EntityManager.getReference0 method of .lPA
i
I
1)It will return 'null'value, if object is not found on cache as well as on database.
I 2) It is early loading, Means when we call session.load(Class, identifier) method it will hit the database immediately and
i load entity object and return entity object.
I
3) As Session.get() returns a fully initialized instance, so it is fully available in any future detached state.
I
, 4) Use this method if it is not s u e that the objects exist.
II
5 ) It is just like EntityManager.find()method of JPA
1
' NOTE: If working with detached objects is not needed, load() or getReference() can be used to have better
1 performance.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
Page 2http://javabynataraj.blogspot.com 41
Hi bei-nate-Session Methods
-,
I NOTE: Session.load() or EntityManager.getReference() should be used if a fully initialized instance is not needed, which
I
, saves a database roundtrip if nothing other than creation of an association is done, with the proxied instance in --
rnailaged state
NOTE: load() method exists prior t o get() method which is added on user request.
.',
4.)HOW to call get and load methods ?
: 50. public void callload(){
51. Session session = SessionUtil.getSession();
j _
52. session.beginTransaction();
53. try { i
1 54. Account account = (Account)session.load(Account.class,9001);
1 55. / / ~ tthis line put Break.point ...Now observe the console, After this line executed, iI
56. //we can't find any select statement. And if observe on the variables window, account object not initialized.
' 57. // Now account isjust a proxy object.
! 58. i
1 59. System.out.println(account.getName());
I 60. //After this line yo" can find select query on the console, And now account object is initialized with database data. 11 61.
( . 62. } catch (ObjectNotFoundException e) { 1
// System.out.println(account.getName{));
//This would fail!!!
publicvoid callGet() {
Sessionsession = SessionUtil.getSession();
session.beginTransaction0;
Account account = (Account) session.gct(Account.class,9001);
// At this line put ~ r e a k.p'oint... Now observe the console, After this line executed,
//we can find select statement. And if observe on the variables window,
//account object initialized with database data
// System.out.println(account.getName());
// no problem!!!
W h e n t o use Session ~ e t 0and load0 i n Hibernate
1.if object present we have t o implement some logic, if not we need t o implement some other logic.
I get(): if the object is not there, it returns null. Then we can implement above requirement as follows
Iif(object == null){
//some code
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
L-- -- - --
An IS0 9001 : 2000 Certified Company IJ -
Page 3http://javabynataraj.blogspot.com 42
~ ~
~p p~ - .... .-
. . Hibernate-Session Methods Mi-.Sel<hai-Reddy !
//some other code
I
I
load(): if the object is not there it throws an exception. So we can't implement this requirerne~itusing load()
For the above requirement we go for get() method.
2. If you we want to use the JavaBean that you are retrieving from the database after the database transaction has been
conimitted, you'll want to use the get method, and quite frankly, that tends to be most of the time. For example, if you
load a User instance in a Servlet, and you want to pass that instance to a Java Server Page for display purposes, you'd
need to use the get method, otherwise, you'd have a LazylnitializationException in your JSP.
3. get() method could suffer performance penalty if only identifier method like getld() is accessed. So consider using
load() method if your code doesn't access any method other than identifier or you are OK with lazy initialization of
object.
Overloaded load0 methods (Hibernate 4.x)
Overloaded get() methods (Hibernate 4.x)
*
cr. getQClasl:clazz; S~l.islizatl:lciclj : c;t,-icct - Sesric1.1
7 .
. .
.- . <::a c~ct(5tringentit:,:l;lstj~~, C.,e1.ializ3t:le il:l,! : l!-jt,~~ct. >c~j!:..:-
...
c..: gct(Clas5 clarz, S~1.13lirabltid: LI=CI.:I'~.:~C!C~EIcckka;ior.le) : Object
,-.
..*:. get(Clar.5 clarz,. Serislisable id,, Lccki?l;tion: Icck0pticn.l : Ot:~!cct
. .
:..:"c~et(Gring tntit;l;,I21-17~5~1-isliz~1:;lci::II Lcckl;~~lccleIcckhlocle) : Ot.:icct
i:.) gtt(Stl.it~g~t~tit:,'l'larr~~.Sel.islizablc iil, Lccl;:Options lc1ck0l:tjct1:> : Object
Q) When update() method has to call ?
Transient state?
Transient state means the object is not associated with session and not presented in database. When there is no record
in the database, no question of updating the record: So when the object is in transient state we can't call update()
method-
Persistent state?
Persistence state means the object is associated with session as well as presented in the database. If the object is in the
persistent state then the object is said to be synchronized with database. 50 whatever modifications done to the object,
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
- An IS0 9001 :2000 Certified Company
Page 4http://javabynataraj.blogspot.com 43
..-- -- . ~ . -~ ~.. -- - -...- .. --
> .
: Hibernate-Session Methods Mr.Sel<harReddv , ' :
/ those changes will be updated in the database and vice versa. So we no need to call update() method when object is in
1
I persistent state. I
' 
, Detached state?
II
Detached state means the object IS not assocrated with session but presented In the database In this state if we want t o 1,
' do any n~odificationsto the object we should call update() method. Because in thls state the object is not synchron~zed
i with database.
I
I public void saveOrUpdate(0biect object) throws HibernateException;I
I
I If the record is not there in the database ~twrll try to insert the record. If the record is there in the database it will try t o ,
! update the record.
1 Pseudo code o f saveorupdate():
1. class Sessionlmplimplements Session{
1 2. public void saveOrUpdate(0bject object){
i 3.
1 4. //SELECT THE RECORD
5. Object obj = session.get(object);
j t: //IF RECORD EXIST
If(obj != null){
// UPDATE THE RECORD
1 :: updatejobj);
, 10. ) else{ // IF RECORD NOT EXIST
11. // INSERTTHE RECORD
I 12. save(obj);
13. /
1 Ex: Table ACCOUNT
Application code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
4. Account account = new Account();
5. account.setAccountld(1001); .
6. account.setName("sekhar");
7. account.setBalance(6800.00);
8.
9. session.saveOrUpdate(account);
10.
11. session.getTransaction().commit();
12.
13. //Now saveorupdate() internally calls save(),becauserecord with 9001id is not available in the database.
Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666, 23734842
l1
IS0 9001 : 2000 Certified Company -
Page 5http://javabynataraj.blogspot.com 44
Application code:
~ .- -...-p---p-pp-.-..p..-- .
Hibernate-Session Methods. ,. .--.
Mr.SeltharRecidy---- ... .. w
Table: ACCOUNT
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
i 4. Account account = new Account();
I 5. account.setAccountld(1001);
6. account.setNarne("selthar Reddy"); I
1 7. account.setBala1ice(8200.00);
8.
9. session.saveOrUpdate(accour~t);
' 10.
11. session.getTransaction().commit();
I 12.
!
i
13. //Now saveorupdate() internally class update(). Because the record with 9001id is already exists in the database.
i
!=NO
,I-
Table:
i
I
ACCOUNT
I 1001 6800
11
NAME
I ACCNO / NAME I BALANCE )
BAL
1 1001 I rekhar Reddy 1 8200 1
I public Connection close0 throws HibernateException;
I
I
Once the transaction is completed we need to close the session. When we close the session all the associated objects I
! with the session will be de-associated from session and associated JDBC connection also closed. It is not strictly necessary to .
close the session but you must at least disconnect() it.
i
'I public void clear();
I
This method is used t o de-associate all the objects from session.
1 Table: ACCOUNT
1002 Kesavareddy 9500
1 Application code:
1. Session session = SessionUtil.getSession();
1 2. session.getTransa~tion(/begin();
- 3.
4. Account accountl = (Account)session.get(Account.class,1001);
1 5. Account account2 = (A~~ount)session.get(Account.cla~~,1002~;
I
6. // Now accountl and account2 objects are in persistent state.
1 7.
8. accountl.setName("new sekhar");
1 9. account2.~etName("newkesavareddy");
10.
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I
An IS0 9001 :2000 Certified Company
-- APage Ghttp://javabynataraj.blogspot.com 45
~
pp ~~ .~
/ Hibernate-Session Methods -. ..
-. , . Mr.SekharReddy --::I ---- !
-.
1 11. session.clear(); I
I 12. //Now account1 and account2 objects are in detached state. !-! 13.
/ 14. session.getTransaction().conimit();
1
~,
1. Session session = Sess~onUtil.getSession();
2. session.getTransaction().begin();
3.
4. Account accountl = (Account)session.get(Account.class,1001);
5. Account account2 = ~Account)session.get(Account.class,1002);
6. // Now accountl and account2 objects are in persistent state.
7.
8. session.clear();
9. //Now accountl and account2 objects are in detached state.
10.
11. accountl.setName("newsekhar");
12. account2.setName("new kesavareddy").
13.
14. session.getTransaction().commit();
After execution:
ACCOUNT
ACCNO BALANCE
sekhar
kesavareddy
1
I i in the above example, when w e call session.clear() method, accountl and account2 objects will be de-associated )
from the session object. i.e. account1 and account2 objects are moved from persistent state t o detached state. I
9 Now accountl and account2 are in non-transactional state. So even we are committing the transaction the modified
I
values of account1and account2 are not updated in the database. iI
/ public void evict(0biect object) throws HibernateException:
i
This method is used de-associates the specified object from session.
Table: ACCOUNT
I
ACCNO BALANCE
1 I 1001 sekhar
1002 kesavareddy 9500 1I I I I
Application code:
1. Session session = SessionUtil.getSession(); r
4. Account account1 = (Account)session.get(Account.class,1001); 1,
5. Account account2 = (Account)session.get(Account.class,1002);
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I
1
An IS0 9001 :2000 Certified Company
Page 1 - I -http://javabynataraj.blogspot.com 46
H ibei-i~ate-SessionMethodsI - - __I.
-- -- Mr.SeltharRedcly.
1
u r i
6. // Now accountl and account2 objects are in persistent state.
I 7.
' 8. accountl.setName("new sekhar");
1 9. acco~1nt2.setName{"1iewkesavareddy");
10.
, 11. session.evict(account1);
1 12. // Now accountl in detached state and account2 in persistent state.
13.
j 14. session.getTransaction().commit();
i After Execution: ACCOUNT
I ACCNO I NAME 1 BALANCE I
1 1001 I sekhar 1 8400 1
I
'i In the above example when w e call session.evict(account1) accountl object will be de-associated from sesslon ,
I
I object.
- 9 After calling transaction.commit(), only account2 object will be updated. Because it is in persistent state.
i 'i evict() is used to de-associate specified object from the session object.
1002 1 new kesavareddy
- !
1 public boolean contains(0bject obiect);
9500 ~
I
It is used t o check whether the object is associated with session or not. I
I I
I Application code: I
I
1. Session session = SessionUtil.getSession();
I 2.
3. Account account = (Account)session.get(Account.class,1001);
I 4. System.~ut.println(~'Aftercallingget() method1');
' 5.
 6. if(session.contains(account)){
. , 7. System.out.println("account Is associated with session");
8. } else{
I 9. System.out.println("accountis not associated with session");
10. }
I 11.
12. session.clear();
13. System.out.println("After calling clear() method");
1 14.
15. if(session.contains(account)){
1 16. Systeni.out.println("account Is associated with session");
17. } else{
1 18. System.out.println("account is not associated with session");
- 19. }
I
i
public boolean isConnected(L
I To check weather there is a connection is associated with the session or not.
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
>
Page 8http://javabynataraj.blogspot.com 47
.- ~ .p..-p---p--.----... . ... - .~.~-~-
-.~
Hibernate-Session Methods Mr.Sel<hai-Reddy - .
1. Session session = SessionUtil.getSession();
2. if(session.isConnected()){
3. System.out.println("connected");
4. }else{
5. System.out.println("not connected");
6. ?
7. session.close();
8. if(session.isConnected()){
9. System.out.println("connected");
lo. }else{
11. System.out.println("not connected");
12. }
public void flush() thicws HibernateException;
This method is used to synchronize session data with database.
1 Application code: I
1. Session session = Sess~onUt~l.getSession();
-
2. session.getTransact~on().begin(); I
3.
4. Account account = (Account)session.get(Account.class,1001); I
I
1 5. account.~etName(~'newsekhar");
( 6. account.setBalance(9500); i
I
7. session.flush();
8.
9. System.out.pr~ntln("Breank..Point and observe the conscle..");
10.
11. session.getTransaction().commit(); I
I
3 In the above example when we call session.flush(), Hibernate checks or compares account object data and ,I
corresponding record database. If it finds difference, it will execute update query to update object data into the [
database record.
I
9 When transaction.commit() is called it will also check object data and corresponding record data. If it f~nds II
different ~twill update object data into database.
9 So after transaction.commit(), we should not call sessioll.flush() because when we call transaction.cornrnit() I
session is in sync w ~ t hdatabase
I,
Batch Processing
i9 The execution of series of programs is called batch processing. Batch processing is the process of read~ngdata --
I
from a persistent store, doing something with the data, and then storing the processed data in the persistent
1
store
9 Usually we run Batch process, when computer resources are less busy.
9 We are using flush() and clear() methods of the Session API for the batch insert process.
I When you need t o upload a large number of records into our database by using hibernate we are using the below code. !
~ - - - - - -
~ a r e si Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 i
1 An IS0 9001 :2000 Certified Com~anvI ---. - a ,
--.,
Page 9http://javabynataraj.blogspot.com 48
_ Hibel-nate-Session MethodsI _
Mr.SeltharReddy. - --
1 Eg:
Session session = SessionUtil.getSession();
Transaction tx = session.beginTransaction();
for ( int i=O; i<1000GO; i++ ) {
Enlployee employee = new Employee(.....);
session.save(employee);
1
The prime step for using the batch processing feature is to set hibernate.jdbc.batch-size as batch size to a number
i either at 20 or 50 depending on object size. This shows the hibernate container that every X rows t o be inserted as
batch.
I
Eg: -
I. Session session = SessionFactory.openSess~on();
- 2. Transaction tx = sess~on.beginTransaction();
/ 3.
- 4 for ( int i=O; ic100000; i++) {
1 5. Ernployee employee = new Employee(. ..);
I 6. session.save(employee);
1 7. if( i % 50 == 0 ) { // Same as the JDBC batch size
I 8. //flush a batch of inserts and release memory:
I 9. session.flush();
I 10. session.clear();
11. }
I 12.1
13.
; 14. tx.commit();i
15. session.close();
I Advantage:- Batch processing helps to resolve the problem of OutOfMemoryException.
I
I
public void flush() throws HibernateException;
II
This method is used t o synchronize the database data with session data. To understand the importance of refresh()
I method observe the following scenarios.
Casel: with single session, single time calling get() method:
I Table:
-
I
I
I Application code:
ACCOUNT
ACCNO BALANCE
sekhar
1 1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
i IVaresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified C o m ~ a n vL -- . .
Page 10http://javabynataraj.blogspot.com 49
. - -. - - - - -
Hibernate-session Methods ~ i - . ~ e l t h a r ~ e d c i y-
3.
4. Account account = (Account) session.get(Account.class, 1001);
5. System.out.println("Before updating the database..."),
6. System.out.pr~ntln("Name: " + account.getNanie());
7. System.out.println("Balance : " + account.getBalance());
8.
,
9. // Break .point. go to database and modify the data
10. ACCOUIVT
I
1 1001 sekhar new 1 9500 7
/ ACCNO ( NAME
I 1
11. System.out.println("After updating the dat~base...");
12. System.out.println("Name : " + account.getName());
13. System.out.println("Balance : " + account.getBalance());
14.
15. session.getTransaction().commit();
16.
17. session.close();
BALANCE 1
1 Output:
Before updaticg the database...
Name : sekhar
Balance : 8400.0
After ~~pdatingthe database...
Name :sekhar
Balance : 8400.0
1 Explanation:
> When we call the get() on session object, it will h ~ tthe database and get the data from the database and creates -
entity object and assign the retrieved data to entity object. And finally that entity object will be cached on the
session object. I
When we update the data on the database it will not get the updated data. Just it always shows session cached I
data.
, I
I CaseZ: with single session, multiple times calling get() method:
Table: ACCOUNT
I I ACCNO 1 NAME 1 BALANCE
L
. ,
--
Page 11
I
Application code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
4. Account account = (Account) session.get(Account.class, 1001);
5. System.out.println("Before updating the database...");
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 :2000 Certified Com~anv
I I
1001 sekhar 8400
http://javabynataraj.blogspot.com 50
Hibernate-Session Methods- -- ---- --MI-.SeltharReddy--
l
8.
9. // Break..point...go to database and mod~fythe data
10. ACCOUNT
m]NAME
I
1 BALANCE 1
/-tsekhar new
1
9500
/ 11. account = (Account) session.get(Account.class, 1001);
12. System.out.println("After updating the database ...");
'
13. Systcm.out.println("Name : " + account.getName());
14. System.out.println("Balance : " + account getBalance0);
I
15.
16. session.getTransaction().cornmit();
I 17.
18. session.close();
- Output:
II
Before updating the database ...
Name : sekhar
-1
Balance : 8400.0
After updating the database...
I Name : sekhar
Balance : 8400.0
/ Explanation:
> When we call the get() on session object(second time), it will check whether the object is available in session or
not. If the object is available in session, it will not hit the database.
> In above example with Accno 1001already account object is already available in session object. That's why even
we call get() method on session object 2ndtime, it will not hit the database. That's why it didn't display the
updated record data of database, instead it displayed previous data only.
Case 3: creating multiple sessions.
Table: ACCOUNT
1 ACCNO 1 NAME 1 BALANCE 1
) 1001 I sekhar 1 8400 1I I I I
Application code:
1. Session session1 = SessionUtil.getSession();
2. Session session2 = SessionUtil.getSession();
3.
4. Account account = (Account) sessionl.get(Account.c~ass,1001);
5. System.out.println("Before updating the database...");
6. Systern.out.println("Name : " + account.getName());
7. Systern.out.println("Balance :" + account.getBalance());
Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
http://javabynataraj.blogspot.com 51
~ - -- . ---- --- --- . .- . ... .. -- - . - ~ . ~- .-.
I Hibernate-Session Methods Mr.Sel<hal-Reddv 1
8.
I
9. // Break..point... go to database and modify the data
ACCOUNT
1 1001 sekhar new 9500 1
I I I
10. account = (Account) session2.get(Account.class, 1001);
I 11. System.out.println("After updating the database ...");
I 12. System.out.println("Name :" + account.getName());
'
13. System.out.println("Balance : " + account.getBalance());
1
I I
I Output:I
j Before updating the database...
/ IVame : sekhar
; Balance : 8400.0
:
After updating the database...
' Name : jekhar new
I Balance :9500.0
i Explanation:
i
! r In the above example, session2 object doesn't have any associated objects. That's why when we call get()
I method on session2, it hit the database and executes the select query and retrieve the record and display the
Ii updated record of database.
i i But here every time we are creating new session object to get the updated Record. To solve the above problem 1
I
1 we can use refresh() method.
Case4: using refresh()
Table:
1
I
ACCOUNT
1 ACCNO ) NAME / BALANCE 1
I I
I 1001 / sekhar 1 8400
I Application code:
1 I/ 1. Session session = SessionUtil.getSession();
I ::Account account = (Account) session.get(Account.cIass, 1001);
4. System.out.println("Before updating the database...");
5. System.out.println("Name :" + account.getName());
6. System.out.println("Balance :" + account.getBalance());
8. // Break..point...go t o database and modify the data
ACCOUNT
1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
ACCNO
I An I S 0 9001 :2000 Certified Com~anv I,
I_
. .-- I
Page 13
INAME BALANCE
http://javabynataraj.blogspot.com 52
Hibernate-Session Methods ---- -- ---- - - - ..,
Mr-SekharReddy
' -2
v-1sekhar new 1 9500 I
9. session.refresh(account);
I
lo. System.out,println("After updating the database ...");
11. System.out.println("Name : " + account getName());
12. System.out.println("Balance : " + account getBalance0);
! Output: I
I Before updating the database... I
I Name : sekhar
Balance : 8400.0
' After updating the database ..
, Name :sekhar new
1 Balance : 9500.0
I
' Explanation:
I > In the above example when we call refresh(), Hibernate compares database data and object data. If it finds any 1
- difference it will again execute select query and update the object data.
-
i public Obiect mergejobiect obiect) throws HibernateException;
Consider the following example,
Table: ACCOUNT
Application Code:
ACCNO
1001
1. session.getTransaction().begin();
2.
3. Account accountl=(Account)session.get(Account.class, 1001);
4.
5. Account account2= new Account();
6. account2.setAccountld(1001);
7. account2.setName("cherry");
8. account2.setBalance(6500);
9.
10. session.update(account2);
11.
12. session.getTransaction~).commit();
, Output: org.hibernate.NonUnique0bjectException: a different object with the same identifier value was already
NAME
sekhar
1 associated with the session: [com.sekharit.hibernate.entity.Account#lOOl]
I
BALANCE
8400
1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23745666,23734842
I-
An IS0 9001 :2000 Certified Company---- -. -- .-
Page 14http://javabynataraj.blogspot.com 53
- ----..- -- - -~-p--.--p---..---.-.---..p.- ~... - - p-. -- - .- ~~
<
Hibernate-Session Methods Mi-.Sel<harRedciy
i
> In the above example, by calling get() method account1object with identifier '1001' will be there in session. And
by calling update()method account2 object with identifier '1001' is also trying to come into session object. It is
I
I the problem. To avoid this we will go for merge().
:ze:% 15:11 1 1 rl .#:I- ~t1:: .:I
.
3:e:z:5.I13i-1 -1-4111114ate1:: 11
I
I
I
I
I
> In the above example, If we use merge() method instead of update() method, we won't get exception. Just
I 1
I I
i 9 We can't place two different objects(of same type) with the same identifier in the sesslon object.
--
_-------- ------ .-/-
I: .311:I: CII-A r~t.I I: -1 111111-1 ;I 'I--.
'-._ /-
.->' -'-.--,,-
----..-- -_--
''------
---- --
,/--
--.-.
( 13i:~ilL.~rlt2<-lIIIUI 2 :y... <.--- --/---
'------ c- -.
-- ----
I
I account2 object data will be updated into database. i
1 > merge() method behave differently in different scenarios. merge() method can insert, update, merge the data. -
1 I
i To understand more clear about merge() method consider the following cases. !
-
I
1 Case 1:merge() method insert the data
I
j Table: ACCOUNT !
I
! BALANCE
I sekhar
Application Code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
4. Account account = new Account();
5. account.setAccountld(1002);
6. account.setName("cherry");
7. account.setBalance(4500.00);
8.
9. session.merge(account);
10.
1 After execution:
I
ACCOUNT
1 ACCNO I NAME 1 BALANCE 1
( 1001 1 Sekhar 1 8400 1
1002 1 cherry 14500 / 1I I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1An IS0 9001 :2000 Certified Company
Page 15http://javabynataraj.blogspot.com 54
-.----- - - - - - -- - ---- -- - - . - -- -
Hibernate-Session Methods Mr.Sel<harRec!dy
I
3 In the above example, when we call merge() method, first it will try to load Account object with identifier 1002,
As we don't have a record in ACCOUNT table with ACCNO#1002, it will insert Account(1002, cherry, 4500.00j
object into database.
. Case 2: merge()method update the data
I
Table: ACCOUNT
ACCNO IVAME
Sekhar
1002 cherry 4500
Application Code:
1. Session session = SessionUtil.getSession();
2. session.getTransact~on().begin();
3.
4. Account account = new Account(),
5. account.setAccountld(1002);
6. account.setName("yeIlareddy");
7. account.setBalance(5600.00);
8.
9. session.merge(account);
10.
11. session.getTransaction().commit();
12.
13. session.close();
1 After executiori: ACCOUNT
I ACCIVO NAME I BALANCE (
Sekhar
yellareddy 5600 i
1 P In the above example, when we call merge()method, first it will try to load Account object with identifier 1002,
As we have a record in ACCOUNT table with ACCNO#1002, it will try to update with latest Account(1002,
- 1 yellareddy, 5600.00) object into database.
I
I Case 3: merge() method merge the detached object data into persistent object
Table: ACCOUNT
1 ACCNO 1 NAME 1 BALANCE 1
Sekhar
yellareddy
Application Code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
4.. Account accountl=(Account)session.get(Account.class, 1001);
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company........... . . . . . . . . . . . . . . . . . . . . . . . ....... ............................ .....
page-%-http://javabynataraj.blogspot.com 55
, ..__ .- .. ---.--~-- -.--.~,
' Hibernate-Session MethodsI -
Mr.SekharReddy .-
.L -, : I
I
,-,
11 5.
1 6. Account account2= new Account(); - ..
1 7. account2.setAccountld(1001);
i 8. account2.setNarne("kesavareddy"); . ~
9, account2.setBalance(6500);
i
I 10. /--.
, 11. session.merge(account2];
12.
I . .
i 13. session.getTransaction().commit();
j 14. session.close();
1 After execution: ACCOUNT
ACCNO BALANCE
yellareddy
I I
,In the above example, Before llthline; accountl is in Persistent state, and account2 in detached state.I . - ,
-
. ,
/ > In the above example, when we call merge() method it will check, weather there i i any object associated with
the session with same identifier(1001). -
> In our example, accountl#1001 object is already associated with session, So merge() method now, Copy the I
< - .
state of accoun2#1001 object state into accountl#1001 object. After llthline also, account1 is in Persistent ,
j
state, and account2 in detached state.
1 3 When the transaction is committed, As acountl#lOOl(Persistent-state)data is modified, so it will hit the update
I
!
query, t o update session data with database.
Q) What is the difference between merge and update? i
i
update () :When the session does not contain an persistent instance with the same identifier, and if it is sure use update I
for the data persistence in hibernate.
i
I
merge (): Irrespective of the state of a session, if there is a need t o save the modifications at any given time, use
I
merge(). !
, public Serialiiable getldentifieriobiect object) throws HibernateException; I
To know the object identifier value at the runtime, we need to call getldentifierfobject object)
I
Application code: 1
I Account account = (Account)session.get(Account.class,1001);
I Serializable id = session.getldentifier (account);
System.out.println("Identifier of Account is :"+ id); '1
1Transaction methods:
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1
An I S 0 9001 :2000 Certified Company
--- I-
Page 17-http://javabynataraj.blogspot.com 56
---- - -- - --- -- - - -pp.--p-- -
- Hibernate-Sessio~~Methods Mr.Sel<harRedcly
I We can apply Transaction management by using transaction object
II
We can get the Transaction object in 2 ways.
Transaction transaction = session.beginTransaction();
I
Transaction transaction = session.getTransaction();
beginTransaction0 return different transaction objects. For each and every request transaction object creates a ~ l c l
begins new transaction context.
I
getTransaction0 return same transaction object for every request. We need to call begin() on transaction objecl l o
begin the transaction
public void persist(0bject object) throws HibernateException;
3 This method is same as save(), but save(object) returns identifier and persist(object) doesn't return any value.
I
i > When we are using generator classes to generate the identifier, At that time if we want to know identifier value
-
which is generated by generator class, then we can go for save() method.
1 3 When we don't want to know generated identifier, then i e can foi persist() method.
. 1.' M e thod Signatures:
public void replicate(0bject object, ReplicationMode replicationMode) throws HibernateException;
This method is used to move the object from detached state to persistent state.
ReplicationMode has attributes described below.
P ReplicationMode.0VERWRITE :this mode reads the processing request and affect the result in database. After
committing the transaction the results are stored in database.
P ReplicationMode.lGN0RE : this mode ignores the processed request. ~ e a n sit doesn't affect the result in
datadase.
r ReplicationMode.LATEST-VERSION :this mode reads the processing request and affect the result in database.
P ReplicationMode.EXCEPTl0N :this mode reads the processing request and affect the result the database.
1 Application Code:
1. Session session = SessionUtil.getSession();
I ;: session.getTransaction().begin();
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I
An IS0 9001 :2000 Certified Company
----
Page 1ghttp://javabynataraj.blogspot.com 57
-- ---..- -. -
Hibernate-Session Methods MrSekharReddv --'
Account account = (Account) session.get(Account.class, 1001);
System.out.println("After get() method");
if (session.contains(account)) {
Systeni.out.println("associated");
1else i
System.out.println("not-associated");
1
session.evict(account);
System.out.println("After evict() method");
if (session.contains(account)){
System.out.println("associated");
} else {
System.out.println("not-associated");
}
session.replicate(account, ReplicationMode.LATEST-VERSIOIV);
Systern.out.println("After replicate()method");
if (~ession.contains(account)){
System.out.println("associated");
} else {
System.out.println("not-associated");
1 public void IockiObiect obiect, LockMode IockMode) throws HibernateException;
i
I If we are updating some group of tables no other person is allowed to update the records on the same table until our
I work is completed. So using lock(), if we lock the record it doesn't allow updating from different users till we commit the
I transaction.
1 Hibernate defines Several lock modes
I P LockMode.NONE :Don't go to the database unless the object isn't in either cache. I
I
3 LockMode.READ : Bypass both levels of cache, and perform a version check to verify the object in memory is
the same version as that currently exits in the databse.
!
1
P LockMode.UPGRADE: Bypass both levels of cache, and perform a version check and obtain a database-level
I
I
I pessimistic loc upgrade lock, if that is supported. I
I
I P LockMode.UPGRADE-NOWAIT: same as UPGRADE , but use a SELECT .... FOR UPDATE NOWAIT on Oracle.
This disables waiting for concurrent lock releases, thus throwing a locking exception can't be obtained.
I
I
-
9 LockMode.WRITE: Is obtained automatically when Hibernate has written t o a row in the current Transaction.
I This is an internal mode and can't bespecified explicitly. 1
I NOTE:this method got deprecated in Hibernate 4.x version I
I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i
h.An IS0 9001 :2000 Certified Company I -
pa e 1 F 'http://javabynataraj.blogspot.com 58
. ~ ~
- ~ ~ . A ~ ~ - . ~ - .~
Hibernate-Multi Database Communication By Mr. SeltharReddy
1 Q.) How to work with MYSQL database? !
I
install the MYSQL database. I
C? Select All Programs 3 MYSQL 3 MYSQL 5.0 3 mysql command line client
I
Give password i
4. In the MYSQL prompt give the following comr-riands
o Create database mydb
I o Use mydbI !
!
6 Now perform database operations normally.
I
C When you open mysql command line client again just give password, and give use mydb command. (don't give !
create database mydb) i
I
I'
Q.)How t o connect t o multiple Databases using Single Configuration File in Hibernate? I
I OracleDataBase Table:
1
I
I SQL> desc account;
i Name Null? TYpe
I -----_----_---_-------------------------- _____-_- ____________ ____
-
1 ACNO IVUMBER(5)
i
BAL NUMBER(8,2)
1 IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
An IS0 9001 :2000 Certified Company-
Pagehttp://javabynataraj.blogspot.com 59
, ~~~ .- ~ ~ ~
~.~ ~ .
I Hibel-nate-Multi Database Commu~~ication
I ---
By Mr. SeltharReddy- ....a..'i
-
1 M y S Q L D a t B e Table
; +----.-.+-.-----.--+----.-+-----+-----------+- - - < - --+
I
I I Field I Type ( Null I Key ( Default I Extra (
I
I 1 acno 1 int(5) 1 YES 1 1 NULL 1 I
i
I
1 name I char(l5) j YES I I NULL ( 1
Account.iava
1. package coin.neo.hibernate .VO;
2.
3 . public class Account (
4. prlvate ~ n taccno;* -
5. prlvate Strlng name;
6. privatedoublebalance;
7.
8. publlc int getAccno0 {
I 9. return accno;
10. 1
j ll.
12. publlc void seiAccno (lnt accIlo) (
13. this.accno = accno;
14. 1
15.
/ 16. public Strrng getName() (
17. return name;
1 18. I
19.
20. public vold setName (String name) [
21. this.name = name;
22. I
23.
24. public double getBalance ( ) [
25. return balance;
26. I
27.
28. public void setBalance(doub1e balance) {
29. thls.balance = balance;
30. I
1 31.
I
Naresh iTechnologies, Opp. Satyam Theatre, ~ r n e e r ~ e t ,Hyderabad, Ph: 040-23746666,23734842 1
An IS0 9001 :2000 Certified Company I -
Page 2http://javabynataraj.blogspot.com 60
~..~.~...................................... . . ~~ --...-- ~
- ~
Hibernate-Multi Database Communication 7By Mr. SekharReddy I
1. package com.neo.hibernate.dao;
2 .
3. import crg.hibernate.Session;
4. lrilport org.hibernate.SessionFactory;
5. import org.hibernate.cfg .C ~ n figuration;
6.
7. import com.neo.hibernate.util.Conn~ctionUti1;
8. import com.neo.hibernate.vo.Account;
9.
10. public class PracticeDao {
11. public static void main(String[] args) {
12.
13. Configuration configuration = new Configuration();
14. configuration.configure("com/neo/hibernate/config/hibernate.cfg.xml");
15. SessionFactcry factory = configuration.buildSessionFactory(j;
16. / / Oracle
17. Sesslon oracleSession =
18. factory.openSession(ConnectionUtil.getOracleConnecti~n());
19. Account oracleAccount = (Account)
20. oracleSession.get(Account.class, 1001);
21. System.out.println("0racle Account table details . . . . ") ;
22. System.out.println("Accno : "+oracleAccount.getAccno());
23. System.out.println("Name : "+oracleAccount.getName());
24. System.out.println("Ba1ance : "+oracleAccount.getBalance()) ;
25. //Mysql
26. Session mysqlSession =
27. factory.openSession(ConnectionUtil.getMysqlConnection()) ;
28. Account mysqlAccount= (Account)mysqlSession.get(Account.class, 1001);
29. System.out.println("Mysq1 Account table details . . . . " );
30. System.out.println("Accno : "-1-mysqlAccount.getAccno()) ;
31. System.out.println ("Name : "+mysqlAccount.getName ( ) ) ;
32. System.out.println("Balance : "+mysqlAccount.getBalance());
33.
34. 1
35. )
36.
ConnectionUtil.iava
1. package com.neo.hibernate.ut11;
2.
3. import java .sql .Connection;
4. import java.sql.DriverManager;
5. lmport java.sql.SQLException;
6.
7. public class ConnectionUtil {
8. static {
9 . try {
10. Class.forName("oracle.jdbc.driver.OracleDriver~');
11. Class.forName("com.mysql.jdbc.Driver");
12. 1 catch (Exception e) {
13. e.printStackTrace0;
14. 1
15.
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 iAn IS0 9001 :2000 Certified Company I
1.-
Page 3http://javabynataraj.blogspot.com 61
.- ~~ ~ - ~- .
( Hibernate-Multi Database Coi~~munication -- By Mr. SekharReddy--- - --.- ..-?I 1,., .
': 16. 1 ,I
public static Con~ectiocget0racleConnection() (
Connection ~ j i 1 i i - j ~ ~ i , 3 : i= 11~11;
try (
connection = Driv?rManager.getConnection(
"jdbc:oracle:thir:: Plocalhost:1521:XEW, "system",
} catch (SQLExcepcion e) (
e.printStaekTrac? ( ) ;
1
return connection;
1
public static Connection ge~MysqlConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:mysql://loca1host:33O6/mydb", "root",
) catch (SQLException e) {
e .printStackTrace ( ) ;
1
I 37. return connectlon;
1 3 8 .
( 39.
' 4 0 . 1
I
"tiger");
'I I
I
i Account.hbrn.xm! 1
1. c?xml version="l.0" encoding="UTF-8"3'. !
1 2. < ! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3 . O / / E l l r ' !
"http://hibernate.sourceforge.neL/!i1berate-mapping-3.O.dtd" >
3.
4 . <hibernate-mapping>
5 . <class name="com.neo.hiberi~ate.vo.Accountr'table=f'ACCOUNT">
6. <id name="accno" column="ACNO"></id>
7. <property name="name"></property>
8 . <property name="balai?ceMcolumn="BAL"></property>
9. </class>
10. </hibernate-mapping>
hibernate.cfg.xml
1. <?xml version='l.Or encoding='UTF-6'?>
2 . <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Conflguratlon DTD
3.@ / / E N u
3. "http://hibernate.sourceforge.net/hibernate-configuration-3.O.dtd"> 1
4. <hibernate-configuration>
5. <session-factory> I
6. <property name="dialect">org.hibernate.dialect.OracleDialect</property> -I
7. <mapping resource="com/neo/h~bernate/mapping/Account.hbm.xmlf'/>
8. </session-factory> I
9. </hibernate-configuration>
I
I
Q.)How to connect to multiple Databases using Multiple Configuration Files in Hibernate?
I
I
IVareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
An IS0 9001 :2000 Certified CompanyI . . . . . . . . . . . . ~ . .. . ... -.- -. .-- 'I
Page 4-'http://javabynataraj.blogspot.com 62
~ i b e r n a t e - ~ u l t iDatabase Con~munication Bv Mr. SelcharReddv
~ r a c l e ~ a t a ~ a s eTable:
i
SQL> desc account; 1
Name Null? TY
i1
......................................... -------- -----------------
ACNO NUMBER(5)
NAME VARCHAR2(10)
BAL NUMBER(8,2)
1 ( Field I Type I Null I Key ( Default I Extra (
+-------+---------- +------+-----+---------+-------+
I I acno 1 int(5) I YES I I NULL 1 I
I ( name ( char(l5) I YES ( ( NULL I 1
I
( bal 1 float 1 YES I I NULL 1 1
' Account.iava
! Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I An IS0 9001 :2000 Certified Company
Page 5-http://javabynataraj.blogspot.com 63
. . . . . - .. . ~ -.,
I Hibernate-Multi Database C o ~ ~ ~ ~ ~ ~ u i ~ i c a t i o n- ....-..- - --- By--Mr. SeltharReddy - -1- , - . . -- I
,,I
1 . package corn.ne2. hibernate. i-c;
2 .
3 . p u b l i c c l a s s Account {
4. p r i v a t e i n t accno;
5 . p r i v a t e S t r i n g n a m ? ;
: 6 . p r i v a t e double balance;
7 .
8 . p u b l i c i n t gethccno ( ) i
1 9 . r e t u r n accno;i
1 0 .
i 1 1 .
/ 1 2 . p u b l i c void set,?ccnc ( i n t ?:cn.:?) :
1 3 . t h i s .accno = -::I::: ;
1 4 . ?
; 1 5 .
1 1 6 . p u b l i c S t r i n g getName() {
1 1 7 . r e t u r n name;
1 1 8 . )
1 9 .
: 2 0 . p u b l i c void setName ( S t r i n g nan~ej {
j 2 1 . this.name = nasa;
i 2 2 . 1
i 2 3 .
1 2 4 . p u b l i c double getBalance0 (
! 2 5 . r e t u r n belance;
i 2 6 . 1
i 2 7 .
j 2 8 . p m l i c void setBalance (double iialance) i
i 2 9 . t h i s . balance = halance;
1 3 0 . 1
: 3 1 .
1 3 2 . )
PracticeDao.iava
1. package com.neo.hib?rnate.dao;
2 . import 0rg:hibernate. Sessj-on;
3. import com.neo.hibernate.util.SessionUti1;
4. import com.neo.hibernate.vo,Account;
5 .
6 . public class PracticeDao {
7 . public static void main(String [I args) {
8. / / Oracle
9. Session oraclesession = SessionUtil.getOracleSession();
1 0 . Account oracleAccount = (Account)oracleSession.get(Account.class,
11. 1001);
1 2 . System.out.println("Oracle Account table details . . . . " ) ;
1 3 . System.out.println ("Accno : "toracleAccount.getAccno ( ) ) ;
14. System.out.println("Name : "toracleAccount.getName());
1 5 . System.out.println("Ba1ance : "toracle~ccount.getBalance());
1 6 . //Mysql
1 7 . Session mysqlSesslon = SessionUtil.getMysqlSession();
1 8 . Account mysqlAccount= (Account)mysq1Session.get(Account.c1ass, 1001);
19. System.out.println("Mysq1 Account table details . . . . " ) ;
2 0 . System.out.println("Accno : "tmysqlAccount.getAccno());
1
1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1
I-.
An IS0 9001 : 2000 Certified Company--- --i
Page 6http://javabynataraj.blogspot.com 64
.~.~ - - ~ -. ~ ~.. ~ ~ ~~ .~
,~ Hibernate-Multi Database Colnmunication By Mr. SeltharReddy
, 21. System.out .prlntln("Name : "tmysqlAccount.aetl.!a:ne( ) ) ;
, 22. System.out.pr~1ltln("5alance: "tmysqlAccount.qer.Balance()) ;
23. 1
2 4 . 1
I SessionUtil.java
- 1. package corr,.neo.hibernate.util;
2.
1 3. import 01-9.hibernate.S-ssion;
4. import org.hibernate.SessionFactory;
1 5. import org.hibernate.cfg .Configuration;i
6. import org .ja:<en.Eunction .ConcatFunction;
1 7.
8. public class SessionUtil {
9.
1 10. private static SessionFactory oraclFactory;
11. private static SessionFactory mysqlFactory;
1 12.I stacic (
13. n r ? c l Factory = new Configuration i : . ranfigure (
. I ;;: "com/neo/hibernate/config/~racle.hibernate.cfg.xml")
-- .buildSessionFactory();
' 1 16. mysqlFactory = new configuration().configure(
, I 17. "corn/neo/hibernate/config/~nys~ql.hibernate.cfg.xml")
- 18. .buildSessionFactory(!;
1 19. 1
20.
 I ;;: public static Session getOracleSession() [
return oraclFactory.openSession();
23. 1
1 24.
25. public static Session getMysqlSession() {
1 26. return mysqlFactory.openSession();
27. 1
28. public static void main(String[] args) {
1 29. System.out.println(getMysqlSession()) ;
30. 1
' 3 1 , !
1 Account.hbm.xrnl
1. <?xml version="l.0" encoding="UTF-8Ir?>
1 2. <!DOCTYPE hibernate-rnapplng PUBLIC "-//Hibernate/HlbernateMapping DTD 3.O//ENU
I "http://h~bernate.sourceforge.net/hibernate-mappng-3.0td">
3.
4. <hibernate-mapping>
5. <class name="corn.neo.hibernate.vo.Account" table="ACCOUNT">
I 6 -
<id name="accno" column="ACNO"></id>
- 7. <property narne="name"></property>
8. <property name="balance" column="BAL1'></property>
1 9. </class>
I
10. </hibernate-mapping>
I I
I Naresh I l.echnolog~es,Opp. Satyam Theatre, Ameerpet, ~ ~ d e r a b a d ,Ph: 040-23746666, 23734842 I
An I S 0 9001 :2000 Certified Company I
I __I
Page 7http://javabynataraj.blogspot.com 65
Hibernate-Multi Database Comn~unication Bv Mr. SeltharReddv :-
2. <!DOCTYPE hibernate-configuration P U B L I C M - / / H i b e r n a t o , i S i b e r n a ~ : e C3:lfiguration DTD
1 3 . O//EN1'
3 . lqhttp://hiberliate.soilrc?forge . n e t / h i b e r n a t e - c o n f i g u r a ; i : ~ ; - .C . 5L?":,
1 4 .
- ,
i 5. <hiberna~-3--;l:~i?i-iil;icat i~:i'.
/ 6. <session-fact~ory;
. .
I 7 .
<proL2;+rL:,: ;:,;fie- ' ' j ~ ~ , ~ ~ ~">erg.l-liberllate.di315~;;.; . i . . i ~ > i i [ ~ ~ - ~ ~ ~ < / p r c p e r t ) / >
' 8. <property !?are="zci~~~eccisn.url ">jdbc:mysql://loca?i~ss:::-- .....- - . . - > j C ; G . ' r i ~ - . . - ~ ' -.-.-.,>,</property>~ --
9. <property name= "coi~nection.usernan~e">root</prope~-t;~:;,
I 10. <prcpert;: n ~ r ~ , ~ - - " ~ ~ ~ : ~ ! ~ i 3 z t 1 i ? ~ . p ~ ~ ~ ~ ~ ~ - d " > t i g e r < / ~ r ~ p e r - ~ : ~ , : ~ ~
/ 11. <property !??me="connection.c'river~class">com.n~ysql.i d b e . D~:I.:;ar</property>
12. <rnappi!?g rescurile= "co!ii/neoihiberna te/nlappii~g...~.?z~i~ci?:r. ?!hi!..<rill" />
1 13. </session-factor!:;
14. </hibernate-c3r.fiauratio~n>
oracle.hibernate.cfa.xml
1. <?xml version= '1.0'encoding= 'UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLICu-//Hibernate/Hiberna~eConfiguration DTD
3.O//EMV
3. "http://hibernate.scurceforqe.net/hibernate-co11figuration-3.O.dtd">
4. < h i b e r n a t e - c c n f i g u r a t i o n >
5 . <session-factory>
6. <property n-1ln~="dia1ect">crg.h~ibernate.dialect.Orac?e9Cialect</property>
i 7 . <property name="cor1nection.url">jdbc:oracle.:thin:@localhcst:1521:XE</property>--
8. . " ~ ' . . ' , " - L . , .- -,.^- ! I - - . > . - , , . . I . ; - .,<.,,-. i3!ne11>S,Stem.',/F : v . , . . - . . . . > - i - : . ' - .
. . ., . . . . . . . . .:-. . L ' . ' - L . '..., P - . L .. . '
<property name= "con~~ection.password">tiger</property>
10. . <property
name=rfconnection.driver~classf'>oracle.jdbc.driver.OracleDriver</property>
12. <mapping resource="corn/neo/hiberna te/rnappinq/Accouli t.hbrii.xml " />
14. </hibernate-configuration>
I
Naresh iTechnologies, Opp. satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 :2000 Certified Company I -
page-g--.-http://javabynataraj.blogspot.com 66
Hibernate-Generators using XML -- -- --- --- - . .
Mr.SekharReddy
I
-- - .--.
-riWI
Generator classes
> Generator classes are used to generate the 'identifier' for a persistent object. i.e. While saving an object into the
I database, the generator Informs to the hibernate that, how the prlrllaly key value for the new record is golng t o
generate
3 Hibernate using different primary key generator algorithms, for each algorithm internally ajava class is there for its
1 implementatiorl
i' .
3 All Generator classes has to implement 'org.hibernate.id,ldentifierGeneratorU interface, And has to override
i generate() metliod. The logic to generate 'identifier' has to write in this method
I > In built-ingere~atorclasses, identifier generation logic has implemerited by using JDBC.
1 > If we want we can write the user defined generator class and it should implement
'org.hibernate.id.ldentifierGenerator' interface and has to override generate() method.
- > To configure generator class we can use <generator /> tag, which is ttie sub element of <id/> tag
- > <generator/> tag has one attribute called "class" with which we can specify generator class-name.
I
i
9 While configuring <generator /> tag in mapping file, if we need to pass anv parameters to generator class then we
! can use <param /> tag, which i s the sub element of <generator/> tag,
1 Example: HEM
<hibernate-niapp~ng> 1
I <class .. > I
~<Id ....>
I 1
<generator class="generator-class-namet'> I
<param name="param-nameH>param-value</param>
I
I
</generator>
I
</rd>
i
1
</class> I
</hibernate-mapping>
I
I I
I
1 The following are the list of main generators we are using in the hibernate framework I
i
1 1. sequence
1 2. assigned
I 3. increment
I 5. seqhilo
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
--
An IS0 9001 :2000 Certified Company- -- -
Pa F I -http://javabynataraj.blogspot.com 67
1 6, identify

7. native
8. uuid
1 9 guid
10.select
11. foregin
I
1 In the above generators list, are used for int,long,short types of primary keys, and uuid, guid are used when the pri~nary
key column type is String type (varchar2)
1.) sequence (or~.hibernate.id.SequenceGenerator)
I
' > This generator class is database dependent it means, we cannot use this generator class for all the database, we
should know whether the database supports sequence or not before we are working with it -
- .
P Not has the support with MySq!
I -
~ P Here we write a sequence and it should be configured in HBM file and while persisting the object in the database ,,
sequence is going to generate the identifier and it will assign to the Id property of persistent object, Then it will store ' :
the persistent object into Database.
NOTE: MYSQL even won't allow to create SEQUENCE Object in that database. Then where is the question of calling that
from hibernate applicat~on?
1
NOTE: When we configured generator class for an entity, then we no need to assign identifier value t o entity object
/
whiie saving the entity. Even we assign the identifier value to entity, it will not consider our assigned value, it will use
I
!
/ generator class generated value as identifier value. It applies to all generator classes.
I
1 Steps to work with "sequence" Renerator
I
Step 1:Create a sequence
1 SQL> CREATE SEQUENCE ACCNO-SEQ START WITH 1000 INCREMENT BY 1
To get next value
SQL> SELECT ACCNO-SEQ.NEXTVAL FROM DUAL;
To get current value
I SQL> SELECT ACCNO-SEQ-CURRVAL FROM DUAL;
Step 2: configure the sequence in hbm file.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
An I S 0 9001 :2000 Certified Company
-. I -
Page 2http://javabynataraj.blogspot.com 68
....... . . . . . . . .-- -- --- ...................... ....... ........ ... -- -
Hibernate-Generators using XM L! -. . . . .-- ---. . .
Mr.SekharReddp., - ,
rims i
II
1 <id name=" accountld " column="ACNO">
<generator class="org.hibernate.id.SequenceGenerator" >
! <param name="sequence">ACCNO-SEQ </param>
</generator>
1 </id>
I (OR)
<id name=" accountld " column="ACCNO">-
1 <generator class="sequenceU/>
</ld>
I
1 NOTE: If we don't configure any sequence name then it will take default sequence name(HIl3ERNATE-SEQUENCE ). But 1
I hibernate won't create the sequence, if already sequence is available with name "HIBERNATE-SEQUENCE", then it is! !I
'
used by hibernate. Otherwise hibernate raises the exception.
I
1 NOTE: But remember, if we enable hbrn2ddl.auto property in hibernate configuration file, then hibernate will create the 1. .- database objects if they are not exist.
I
NOTE: It is not advisable to use the default sequence, always prfer to create a different sequence to each enitity 1I seperately. I
I
1 Step 3: Create the entity and save it without assigning identifier.
i1
1. Session session = SessionUtil.getSession();
I 2 . session.getTransaction ( ) .begin( ) ;
3.
1 4. Account account = new Account ( ) ;
5. account.setName ("sekhar");
1 6. account.setBalance (5000);
- 7 .
8. Serializable id = session.save (account);
I 9 .
10. System.out.println (flAccountis created with accno : "+id);
( 11. session.getTransaction ( ) .commit ( ) ;
I Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, ~ ~ d e r a b a d ,Ph: 040-23746666, 23734842
I
I
An IS0 9001 : 2000 Certified CompanyI
Page 3-
1http://javabynataraj.blogspot.com 69
-- - -- -- - -- - --
; Hibei-nate-Generators using XML Mr.SekharRecici,__
IVOTE: When we execute the above code, we can find the sequence execution query on the console, which is used to get
identifier for the saving enitity.
1 Internal Code
1 public class SequenceGenerator implements PersistentldentifierGenerator, Configurable {
I public static final String SEQUENCE = "sequence";
I
.1 public void configure(. .){
I sequenceName = PropertiesHelper.getString(SEQUENCE, params,
"hibernate-sequence"); // default sequence name
parameters = params.getProperty(PARAMETERS);
1
public Serializable generate(. . . ) {
Preparedstatement st =. . ..prepareSelectStatement(sql);
Resultset rs = st.executeQuery();
rs.next();
Serializable result = . . iterate results...
return result;
1
1
I
NOTE: ow onwards for the following generator classes Ijust give the HBM configuration, you can u;e the same entity
saving logic(which we used in the above example as part of step-3) to test them.
/ 9 This generator supports in all the databases
I
I 9 This is the default generator class used by the hibernate, if we do not specify <generator/> element under <id/>
1 element, then hibernate by default assumes it as "assigned" generator class.
9 If generator class is assigned, then the programmer is responsible for assigning the identifier value to entity before
saving into the database
I
1 . HBM:
<id name=" accountld " column="ACCNO">
<generator class="org.hibernate.id.Assigned"/>
</id >
(OR)
! I
Naresh i Technologies, Opp. Satyam 'Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1
An I S 0 9001 :2000 Certified Company , -
Page 4--'http://javabynataraj.blogspot.com 70
--- ---- - . . ~ ~ . - ~ ~ ~ . ... - - - .~ --I
' Hibernate-Generators using XM-- L -- Mr.SekharReddy. .- -- .- 1,
. . . -%a
I-
<id name=" accountld " column="ACCNO" />
Internal Code: I
public class Assigned implements Identif~erGenerator,Conf~gurable{
public Serializable generate(... ){
final Serializable id = . . . get the developer glven id.
if (id==null){
throw new Identif~erGenerat~onException(
"ids for this class must be manually assigned before calling save():" t entityName);
1I
return id;
1
i }
I
NOTE. Whrle testing don't asslgne ident~fiervalue to entity and then try to save entity then ~tthrowsI -
IdentifierGenerationException.
!
NOTE: While testing with assigned generator class, identifier type in enity should be some object type rather than iII primitive type.
!
I
'
> This generator supports in all the databases, so it is database independent generator class.
I I This generator is used for generating the id value for the new record by using the formula
Max of id value in Database + 1
i
> If there is no record initially in the database, then for the first time this will saves primary key value as 1. 1
I i
. HBM:
<id name="accountld" column="ACCNO">
II
<generator class="increment" />
</id>
I (OR)
1
<id name=" accountld " column="ACCNO">
I <generator class=" org.hibernate.id.lncrementGenerator " />
I
</id>
1 Internal Code:
;:;+ -*!v-.5 *>:.,;. .;, ,x :, ~ :.,,<,;: ..,.. .-...--.-<!..:;.....-r@
I public class ~;@$@;@<~~tJj:$?~g.~$~~~$implements IdentifierGenerator, Configurable {
-
~ public synchronized Serializable generate(. . .){
I i f (sql!=null) {
getNext( session );
I 1
return ...final number after adding '1'
,-I Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
...-. ---. --.......- ...... .... . ..-...---
An I S 0 9001 :2000 Certified Company-~~ .----. -
Pages-http://javabynataraj.blogspot.com 71
~ ~.~ - ~ ~. . - -. . -..---.-
,-3
1 Hibernate-Generators using XML Mr.Sel<harReddy_-.,
public void configure(. . .) {
sql = "select max(" + column + ") from " + buf.toString();
I
private void getNext( Sessionlmplementor session ) {
!
Preparedstatement st = ....prepareSelectStatement(sql);
Resultset rs = st.executeQuery();
if ( rs.next() ) {
next = rs.getLong(1) + 1;
1
1 The HiLo Algorithm -
I The HiLo (High/Low) algor~thmknows how to generate unique number series using t w o values: the high and the low. I
-Ihe high value is used as a base for a series (or range) of numbers, while the size of this series is donated by the low
1 value. A unique series is generated using the following steps: I
I
' 1) Load the and atomically increment the high value 1
2) Multiple the high value by the low value (max*low), the result is the first number (lower bound) of the current series
3) The last number (higher bound) of the current series is donated by the following calculation: (max*low)+low-1 I
4) When a client needs to obtain a number the next one from the current is used, once the entire series has been
/ exhausted the algorithm goes back to step 1
6'
1
I
I
I Example: suppose that the current high value in the database is 52 and the low value is configured to be 32,767. When I
the algorithm starts is loads the high value from the database and increments it in the same transaction (the new high I
value in the database is now 53). The range of the current numbers series can now be calculated:
1
I Lower bound = 52*32767 = 1,703,884
I Upper bounds = 1,703,884+32,767-1= 1,736,650 1
All of the numbers in the range of 1,703,884 to 1,736,650 can be safely allocated t o clients, once this keys pool has been
1exhausted the algorithm needs to accessthe database again to allocate a new keys pool. This time the hiih value is 53
(immediately incremented t o 54) and the keys range is:
I
Lower bound = 53*32,767 = 1,736,651
Upper bounds = 1,736,651+32,767-1 = 1,769,417
And so on
IThe big advantage of this algorithm is keys preallocation which can dramatically improve performame. Based on the low I
I I
IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1
I-An IS0 9001- : 2000 Certified Company _I-
Page 6http://javabynataraj.blogspot.com 72
-- -- -- - - ---- - - -- .- --- -- ---- -- -- -- -- -- ----
Hibernate-Generators using XM L M1-.Seltl?arReddy ,
value we can control the database hit ratio. As illustrated using the 32,767 we hit the database only once in a 32,767
, ' generated keys. The downside (at least by some people - but in my opinion this is a none-issue)is that each time the
algorithm restarts it leaves a 'hole' in the keys sequence.
Hibernate has several HiLo based generators: TableHiLoGenerator, MuItipleHiLoPerTableGecierator,
, SequenceHiLoGenerator
TableHiLoGenerator
A simple HiLo generator, uses a table to store the HiLo high value. The generator accepts the following parameters
I o table -the table name, defaults to 'hibernate-unique-key'
I o column -the name of the column to store the next high value, defaults to 'next-hi'
o max-low - the low number (the range) defaults to 32,767 (Short.MAX-VALUE)I
i
A table HiLogenerator which can store multiple key sets (multiple high values each for a different entity). This is useful
!
when we need each entity (or some of the entities) has its own keys range. It supportsthe following parameters:
I
o table - the table name, default t o 'hibernate-sequences'
1 o primary-key-column - key column name, defaults to 'sequence-name'
o value-column - the name of the column to store the next high value, defaults to 'sequence-next-hi-value'
,
o primary-key-value - key value for the current entity (or current keys set), default to the entity's primary table
name
/ o primary-key-length - length of the key column in DB represented as a varchar, defaults to 255
o max-low - the low numer (the range) defaults to 32,767 (Short.MAX-VALUE)
II
The generator uses a single table to store multiple high values (multiple series), when having multiple entities using the
I same generator Hibernate matches an entity to a high value using the primary-key-value which is usually the entity
name. A sample table can look like
I Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified CompanyI
Page 7http://javabynataraj.blogspot.com 73
.~ .~ ............ .-.-pp--p----.---pp- ........... .....
r Hibernate-Generators using XM L MI-.Sel<harRecldv'1
A simple HiLo generator but instead of a table uses a sequence as the high value provider.
o sequence - the sequence name, defaults to 'hibernate-sequence'
o max-low - the low number (the range) defaults to 9.
, r This generator is database independent
, r hilo uses a hi/lo alogorithm t o generate ~dent~f~ers.
1 r Hilo algorithm generate identifiers based on the given table and column(stores high value). Default table is
'hibernate-unique-key' column is 'next-hi'.
I
HBM:
I -I < ~ dname="accountld" column="ACCNO">
<generator class="hilo" >
<param name="table">HIGH-VAL-TAB</param>
, <param ndme="column">HIGH-VAL-COL</param>
I Internal code
! class TableHiLoGenerator extends TableGenerator {
I
I
1 class TableGenerator {
I
i
i
public static final String COLUMN = "column";
public static final String DEFAULT-COLUMN-NAME = "next-hi";
II
i public static final String TABLE = "table";
public static final String DEFAULT-TABLE-NAME = "hibernate-unique-key"; 1
3 It is just like hilo generator class, But hilo generator stores its high value in table, where as seqhilo generator
I
stors its high value in sequence.
I
IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
L. An IS0 9001 :2000 Certified Company I
Page 8http://javabynataraj.blogspot.com 74
.-- --.--... . ~~ ~ -~~ .~ ~~ -.-~ ~~ ~ . . . . .
. . , Hibernate-Gelieratol-s using XML Mr.SeltliarReddg7
1 HBM:I -
<id name="accountld" column="ACNO">
<generator class="seqhilo" >
I <param name="sequence">~~~~~-SEQ</param>
<param name="max-lo">S</param>
</generator>
</ld>
(OR)
1 <id name=" accountld " coiumn="ACCNO"~
<generator class="seqhiloU>
<param name="org.hibernate.id.SequenceHiLoGenerator ">ACCNO-SEQ</param>
i <param name="max-lo">5</param>
</generator>
1 </id>
Q.) How t o work with MYSQL database?
a install the MYSQL database.
c3 Select All Programs 3 MYSQL 3 MYSQL 5.0 3 mysql command line client
a Give password
In the IMYSQL iiomp't give the following commands
o create database mydb
o use mydb
Now perform database operations normally.
c3 When we login to database next time onwards don't give create database command, just give use command.
9 This is database dependent, actually it's not working in oracle.
9 Identity columns are support by DB2, MYSQL, SQL SERVER, SYBASE and HYPERSYNCSQLdatabases.
9 This identity generator doesn't needs any parameters to pass
Syntax t o create identity columns in MYSQL database:
CREATE TABLE STUDENT(
SNO INT(10) NOT NULLAUTO-INCREMENT,
COURSE CHAR(2O),
FEE FLOAT,
NAME CHAR(20),
PRIMARY KEY (SNO)
1
HBM:
1 <id name=" accountld " column="ACNO">--
<generator class="identity" />
1 </id>
/ Example: To create identity columns in MYSQL database.
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
!
An I S 0 9001 :2000 Certified Company
:I
page9 --http://javabynataraj.blogspot.com 75
- .-..- - -- - -- --- - ----- ---- --
Hibernate-Generators using XML---- ~ i - . ~ e k h a r ~ e d d'-
. I
7.)native
I
3 native is not having any generator class because, it uses internally identity or sequence or hilo generator
classes. I
P native picks up identity or sequence or hilo generator class depending upon the capabiliti2s of the underlying * I
database. I
-
HBM:
<id name="accountld" column="ACIVO">
IIVareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
An I S 0 9001 :2000 Certified Company
-1
Page 10http://javabynataraj.blogspot.com 76
Hibernate-Generators using;XML
NOTE: test with niysql and oracle
1 C3 If we connect to mysql it takes identity.
C3 If we connect to oracle it takes sequence.
I
I d uuid uses a 128-b~tuuid algorithm to generate identifiers of type string.
I d uuid generated identifier is unique with in a network.
I c3 uuid algorithm generates identifier using IP address. .,.
C3 uuid algor~thmencodes identifier as a string(hexadecima1digits) of length 32.
1 C3 Generally uuld is used to generate passwords.
1 HBM:
- <id name="accountld" column="ACNO">
~ <generator class="uuid" >
- </generator>
</id>
<id name=" accountld " column="ACCNO">
<generator class="org.hibernate.id.UUIDHexGenerator " >
</generator>
1 </id>
'
select: select retrieves a primary key assigned by a database trigger by selecting the row by some unique key and
I
1 retrieving the primary key value.
I
I
1
I guid: uses a database generated guid string on MS-SQL and MYSQL. I
foreign: foreign uses the identifier of another associated object. Usually uses in conjunction with a <one-to-one>
I primary key association. I
- User Defined Generator class
-
When we feel the existing generator classes are not fit for our requirement, then we will go for user defined
I
I generator class.
1 Steps t o implement user defined generator class. i
i
1 Step 1:Take any java class and implement org.hibernate.id .IdentifierGenerator and override generate() method. In this 1
I
method implement the identifier generation logic as per the requirement. I
I
I - I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
I
An IS0 9001 :2000 Certified Company -.-
Page 11http://javabynataraj.blogspot.com 77
http://javabynataraj.blogspot.com 78
http://javabynataraj.blogspot.com 79
http://javabynataraj.blogspot.com 80
http://javabynataraj.blogspot.com 81
http://javabynataraj.blogspot.com 82
http://javabynataraj.blogspot.com 83
http://javabynataraj.blogspot.com 84
http://javabynataraj.blogspot.com 85
http://javabynataraj.blogspot.com 86
http://javabynataraj.blogspot.com 87
http://javabynataraj.blogspot.com 88
http://javabynataraj.blogspot.com 89
http://javabynataraj.blogspot.com 90
http://javabynataraj.blogspot.com 91
http://javabynataraj.blogspot.com 92
http://javabynataraj.blogspot.com 93
http://javabynataraj.blogspot.com 94
http://javabynataraj.blogspot.com 95
http://javabynataraj.blogspot.com 96
http://javabynataraj.blogspot.com 97
http://javabynataraj.blogspot.com 98
http://javabynataraj.blogspot.com 99
http://javabynataraj.blogspot.com 100
http://javabynataraj.blogspot.com 101
http://javabynataraj.blogspot.com 102
http://javabynataraj.blogspot.com 103
http://javabynataraj.blogspot.com 104
http://javabynataraj.blogspot.com 105
http://javabynataraj.blogspot.com 106
http://javabynataraj.blogspot.com 107
http://javabynataraj.blogspot.com 108
http://javabynataraj.blogspot.com 109
http://javabynataraj.blogspot.com 110
http://javabynataraj.blogspot.com 111
http://javabynataraj.blogspot.com 112
http://javabynataraj.blogspot.com 113
http://javabynataraj.blogspot.com 114
http://javabynataraj.blogspot.com 115
http://javabynataraj.blogspot.com 116
http://javabynataraj.blogspot.com 117
http://javabynataraj.blogspot.com 118
http://javabynataraj.blogspot.com 119
http://javabynataraj.blogspot.com 120
http://javabynataraj.blogspot.com 121
http://javabynataraj.blogspot.com 122
http://javabynataraj.blogspot.com 123
http://javabynataraj.blogspot.com 124
http://javabynataraj.blogspot.com 125
http://javabynataraj.blogspot.com 126
http://javabynataraj.blogspot.com 127
http://javabynataraj.blogspot.com 128
http://javabynataraj.blogspot.com 129
http://javabynataraj.blogspot.com 130
http://javabynataraj.blogspot.com 131
http://javabynataraj.blogspot.com 132
http://javabynataraj.blogspot.com 133
http://javabynataraj.blogspot.com 134
http://javabynataraj.blogspot.com 135
http://javabynataraj.blogspot.com 136
http://javabynataraj.blogspot.com 137
http://javabynataraj.blogspot.com 138
http://javabynataraj.blogspot.com 139
http://javabynataraj.blogspot.com 140
http://javabynataraj.blogspot.com 141
http://javabynataraj.blogspot.com 142
http://javabynataraj.blogspot.com 143
http://javabynataraj.blogspot.com 144
http://javabynataraj.blogspot.com 145
http://javabynataraj.blogspot.com 146
http://javabynataraj.blogspot.com 147
http://javabynataraj.blogspot.com 148
http://javabynataraj.blogspot.com 149
http://javabynataraj.blogspot.com 150
http://javabynataraj.blogspot.com 151
http://javabynataraj.blogspot.com 152
http://javabynataraj.blogspot.com 153
http://javabynataraj.blogspot.com 154
http://javabynataraj.blogspot.com 155
http://javabynataraj.blogspot.com 156
http://javabynataraj.blogspot.com 157
http://javabynataraj.blogspot.com 158
http://javabynataraj.blogspot.com 159
http://javabynataraj.blogspot.com 160
http://javabynataraj.blogspot.com 161
http://javabynataraj.blogspot.com 162
http://javabynataraj.blogspot.com 163
http://javabynataraj.blogspot.com 164
http://javabynataraj.blogspot.com 165
http://javabynataraj.blogspot.com 166
http://javabynataraj.blogspot.com 167
http://javabynataraj.blogspot.com 168
http://javabynataraj.blogspot.com 169
http://javabynataraj.blogspot.com 170
http://javabynataraj.blogspot.com 171
http://javabynataraj.blogspot.com 172
http://javabynataraj.blogspot.com 173
http://javabynataraj.blogspot.com 174
http://javabynataraj.blogspot.com 175
http://javabynataraj.blogspot.com 176
http://javabynataraj.blogspot.com 177
http://javabynataraj.blogspot.com 178
http://javabynataraj.blogspot.com 179
http://javabynataraj.blogspot.com 180
http://javabynataraj.blogspot.com 181
http://javabynataraj.blogspot.com 182
http://javabynataraj.blogspot.com 183
http://javabynataraj.blogspot.com 184
http://javabynataraj.blogspot.com 185
http://javabynataraj.blogspot.com 186
http://javabynataraj.blogspot.com 187
http://javabynataraj.blogspot.com 188
http://javabynataraj.blogspot.com 189
http://javabynataraj.blogspot.com 190
http://javabynataraj.blogspot.com 191
http://javabynataraj.blogspot.com 192
http://javabynataraj.blogspot.com 193
http://javabynataraj.blogspot.com 194
http://javabynataraj.blogspot.com 195
http://javabynataraj.blogspot.com 196
http://javabynataraj.blogspot.com 197
http://javabynataraj.blogspot.com 198
http://javabynataraj.blogspot.com 199
http://javabynataraj.blogspot.com 200
http://javabynataraj.blogspot.com 201
http://javabynataraj.blogspot.com 202
http://javabynataraj.blogspot.com 203
http://javabynataraj.blogspot.com 204
http://javabynataraj.blogspot.com 205
http://javabynataraj.blogspot.com 206
http://javabynataraj.blogspot.com 207
http://javabynataraj.blogspot.com 208
http://javabynataraj.blogspot.com 209
http://javabynataraj.blogspot.com 210
http://javabynataraj.blogspot.com 211
http://javabynataraj.blogspot.com 212
http://javabynataraj.blogspot.com 213
http://javabynataraj.blogspot.com 214
http://javabynataraj.blogspot.com 215
http://javabynataraj.blogspot.com 216
http://javabynataraj.blogspot.com 217
http://javabynataraj.blogspot.com 218
http://javabynataraj.blogspot.com 219
http://javabynataraj.blogspot.com 220
http://javabynataraj.blogspot.com 221
http://javabynataraj.blogspot.com 222
http://javabynataraj.blogspot.com 223
http://javabynataraj.blogspot.com 224
http://javabynataraj.blogspot.com 225
http://javabynataraj.blogspot.com 226
http://javabynataraj.blogspot.com 227
http://javabynataraj.blogspot.com 228
http://javabynataraj.blogspot.com 229
http://javabynataraj.blogspot.com 230
http://javabynataraj.blogspot.com 231
http://javabynataraj.blogspot.com 232
http://javabynataraj.blogspot.com 233
http://javabynataraj.blogspot.com 234
http://javabynataraj.blogspot.com 235
http://javabynataraj.blogspot.com 236
http://javabynataraj.blogspot.com 237
http://javabynataraj.blogspot.com 238
http://javabynataraj.blogspot.com 239
http://javabynataraj.blogspot.com 240
http://javabynataraj.blogspot.com 241
http://javabynataraj.blogspot.com 242
http://javabynataraj.blogspot.com 243
http://javabynataraj.blogspot.com 244
http://javabynataraj.blogspot.com 245
http://javabynataraj.blogspot.com 246
http://javabynataraj.blogspot.com 247
http://javabynataraj.blogspot.com 248
http://javabynataraj.blogspot.com 249
http://javabynataraj.blogspot.com 250
http://javabynataraj.blogspot.com 251
http://javabynataraj.blogspot.com 252
http://javabynataraj.blogspot.com 253
http://javabynataraj.blogspot.com 254
http://javabynataraj.blogspot.com 255
http://javabynataraj.blogspot.com 256
http://javabynataraj.blogspot.com 257
http://javabynataraj.blogspot.com 258
http://javabynataraj.blogspot.com 259
http://javabynataraj.blogspot.com 260
http://javabynataraj.blogspot.com 261
http://javabynataraj.blogspot.com 262
http://javabynataraj.blogspot.com 263
http://javabynataraj.blogspot.com 264
http://javabynataraj.blogspot.com 265
http://javabynataraj.blogspot.com 266
http://javabynataraj.blogspot.com 267
http://javabynataraj.blogspot.com 268
http://javabynataraj.blogspot.com 269
http://javabynataraj.blogspot.com 270
http://javabynataraj.blogspot.com 271
http://javabynataraj.blogspot.com 272
http://javabynataraj.blogspot.com 273
http://javabynataraj.blogspot.com 274
http://javabynataraj.blogspot.com 275
http://javabynataraj.blogspot.com 276
http://javabynataraj.blogspot.com 277
http://javabynataraj.blogspot.com 278
http://javabynataraj.blogspot.com 279
http://javabynataraj.blogspot.com 280
http://javabynataraj.blogspot.com 281
http://javabynataraj.blogspot.com 282
http://javabynataraj.blogspot.com 283
http://javabynataraj.blogspot.com 284
http://javabynataraj.blogspot.com 285
http://javabynataraj.blogspot.com 286
http://javabynataraj.blogspot.com 287
http://javabynataraj.blogspot.com 288
http://javabynataraj.blogspot.com 289
http://javabynataraj.blogspot.com 290
http://javabynataraj.blogspot.com 291
http://javabynataraj.blogspot.com 292
http://javabynataraj.blogspot.com 293
http://javabynataraj.blogspot.com 294
http://javabynataraj.blogspot.com 295
http://javabynataraj.blogspot.com 296
http://javabynataraj.blogspot.com 297
http://javabynataraj.blogspot.com 298
http://javabynataraj.blogspot.com 299
http://javabynataraj.blogspot.com 300
http://javabynataraj.blogspot.com 301
http://javabynataraj.blogspot.com 302
http://javabynataraj.blogspot.com 303
http://javabynataraj.blogspot.com 304
http://javabynataraj.blogspot.com 305
http://javabynataraj.blogspot.com 306
http://javabynataraj.blogspot.com 307
http://javabynataraj.blogspot.com 308
http://javabynataraj.blogspot.com 309
http://javabynataraj.blogspot.com 310
http://javabynataraj.blogspot.com 311
http://javabynataraj.blogspot.com 312
http://javabynataraj.blogspot.com 313
http://javabynataraj.blogspot.com 314
http://javabynataraj.blogspot.com 315
http://javabynataraj.blogspot.com 316
http://javabynataraj.blogspot.com 317
http://javabynataraj.blogspot.com 318
http://javabynataraj.blogspot.com 319
http://javabynataraj.blogspot.com 320
http://javabynataraj.blogspot.com 321
http://javabynataraj.blogspot.com 322
http://javabynataraj.blogspot.com 323
http://javabynataraj.blogspot.com 324
http://javabynataraj.blogspot.com 325
http://javabynataraj.blogspot.com 326
http://javabynataraj.blogspot.com 327
http://javabynataraj.blogspot.com 328

More Related Content

What's hot (20)

PDF
Overview of React.JS - Internship Presentation - Week 5
Devang Garach
 
PPTX
Java Spring Framework
Mehul Jariwala
 
PPTX
iOS Architecture
Jacky Lian
 
PPTX
Express js
Manav Prasad
 
PPT
Spring AOP
Lhouceine OUHAMZA
 
PDF
ReactorKit으로 단방향 반응형 앱 만들기
Suyeol Jeon
 
PDF
Basic Java Programming
Math-Circle
 
PPTX
Interesting Facts About Javascript
Manish Jangir
 
PDF
React js
Rajesh Kolla
 
ODP
Django for Beginners
Jason Davies
 
PDF
Android animation
Krazy Koder
 
PDF
Wordpress 権限昇格の脆弱性について
Yu Iwama
 
PPTX
Appium banking automation
pavithz
 
PPTX
MERN PPT
NeerajGupta96647
 
PDF
Spring core module
Raj Tomar
 
DOCX
Hibernate notes
Rajeev Uppala
 
PDF
Introduction to java (revised)
Sujit Majety
 
PDF
React and redux
Mystic Coders, LLC
 
PPTX
SessionTrackServlets.pptx
Ranjeet Reddy
 
Overview of React.JS - Internship Presentation - Week 5
Devang Garach
 
Java Spring Framework
Mehul Jariwala
 
iOS Architecture
Jacky Lian
 
Express js
Manav Prasad
 
Spring AOP
Lhouceine OUHAMZA
 
ReactorKit으로 단방향 반응형 앱 만들기
Suyeol Jeon
 
Basic Java Programming
Math-Circle
 
Interesting Facts About Javascript
Manish Jangir
 
React js
Rajesh Kolla
 
Django for Beginners
Jason Davies
 
Android animation
Krazy Koder
 
Wordpress 権限昇格の脆弱性について
Yu Iwama
 
Appium banking automation
pavithz
 
Spring core module
Raj Tomar
 
Hibernate notes
Rajeev Uppala
 
Introduction to java (revised)
Sujit Majety
 
React and redux
Mystic Coders, LLC
 
SessionTrackServlets.pptx
Ranjeet Reddy
 

Similar to Hibernate complete notes_by_sekhar_sir_javabynatara_j (20)

PPTX
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
PPTX
Hibernate in Action
Akshay Ballarpure
 
PDF
Hibernate 3
Rajiv Gupta
 
PDF
Hibernate Interview Questions | Edureka
Edureka!
 
PDF
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Jayarajus
 
PDF
Free Hibernate Tutorial | VirtualNuggets
Virtual Nuggets
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPT
Hibernate
Murali Pachiyappan
 
PPT
Hibernate jj
Joe Jacob
 
PDF
What is hibernate?
kanchanmahajan23
 
DOCX
What is hibernate?
kanchanmahajan23
 
PPTX
Session 39 - Hibernate - Part 1
PawanMM
 
PPT
Basic Hibernate Final
Rafael Coutinho
 
DOC
Hibernate tutorial for beginners
Rahul Jain
 
PPTX
Hibernate in XPages
Toby Samples
 
PPT
Hibernate basics
AathikaJava
 
PPT
Java Hibernate Basics
DeeptiJava
 
PPTX
Hibernate
Prashant Kalkar
 
PPSX
Hibernate - Part 1
Hitesh-Java
 
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
Hibernate in Action
Akshay Ballarpure
 
Hibernate 3
Rajiv Gupta
 
Hibernate Interview Questions | Edureka
Edureka!
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Jayarajus
 
Free Hibernate Tutorial | VirtualNuggets
Virtual Nuggets
 
Hibernate tutorial
Mumbai Academisc
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Hibernate jj
Joe Jacob
 
What is hibernate?
kanchanmahajan23
 
What is hibernate?
kanchanmahajan23
 
Session 39 - Hibernate - Part 1
PawanMM
 
Basic Hibernate Final
Rafael Coutinho
 
Hibernate tutorial for beginners
Rahul Jain
 
Hibernate in XPages
Toby Samples
 
Hibernate basics
AathikaJava
 
Java Hibernate Basics
DeeptiJava
 
Hibernate
Prashant Kalkar
 
Hibernate - Part 1
Hitesh-Java
 
Ad

More from Satya Johnny (20)

PDF
Android sai tech (2)
Satya Johnny
 
PDF
Android sai tech
Satya Johnny
 
PDF
Android sai tech (2)
Satya Johnny
 
PDF
Android sai tech
Satya Johnny
 
PDF
Linux admin
Satya Johnny
 
PDF
Linux by zoom tech
Satya Johnny
 
PDF
Linux lab manual by zoom
Satya Johnny
 
PDF
Php naresh technologies
Satya Johnny
 
PDF
Php naresh technologies
Satya Johnny
 
PDF
Php peers
Satya Johnny
 
PDF
Xml naresh tech
Satya Johnny
 
PDF
Php naresh technologies
Satya Johnny
 
PDF
Php peers
Satya Johnny
 
PDF
Php peers
Satya Johnny
 
PDF
Xml naresh tech
Satya Johnny
 
PDF
Php naresh technologies
Satya Johnny
 
PDF
Durga soft scjp-notes-part-2-javabynataraj
Satya Johnny
 
PDF
Hibernate natraj - satya
Satya Johnny
 
PDF
Core java kvr - satya
Satya Johnny
 
PDF
Spring and hibernate santosh'.pdf
Satya Johnny
 
Android sai tech (2)
Satya Johnny
 
Android sai tech
Satya Johnny
 
Android sai tech (2)
Satya Johnny
 
Android sai tech
Satya Johnny
 
Linux admin
Satya Johnny
 
Linux by zoom tech
Satya Johnny
 
Linux lab manual by zoom
Satya Johnny
 
Php naresh technologies
Satya Johnny
 
Php naresh technologies
Satya Johnny
 
Php peers
Satya Johnny
 
Xml naresh tech
Satya Johnny
 
Php naresh technologies
Satya Johnny
 
Php peers
Satya Johnny
 
Php peers
Satya Johnny
 
Xml naresh tech
Satya Johnny
 
Php naresh technologies
Satya Johnny
 
Durga soft scjp-notes-part-2-javabynataraj
Satya Johnny
 
Hibernate natraj - satya
Satya Johnny
 
Core java kvr - satya
Satya Johnny
 
Spring and hibernate santosh'.pdf
Satya Johnny
 
Ad

Recently uploaded (20)

PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Digital Circuits, important subject in CS
contactparinay1
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 

Hibernate complete notes_by_sekhar_sir_javabynatara_j

  • 1. Hibernate For Evaluation Only. Copyright (c) by Foxit Software Company, 2004 - 2007 Edited by Foxit PDF Editor
  • 2. .-. -. pp.pp.--p.- ~ ... -. . . . ~ . - .. . - 1 Hibernate-Introduction Mr.Sek11arReddy, - - -. x. Q) Where actually java is used? Q Java is used to develop the enterprise applications Q Enterprise means business organization * Business organization provides servic2s ! 1 Q) What is Enterprise Application? * Computerizing business services , . 1 Architecture of Enterprise Application - . - I Controller Layer I Client Layer -. Presentation II I 1 Layer I + . a < * . : " - J :I--..- - _ " I 1 Client Layer: I i 3 It is browser software. 1 Controller Layer: 1 P Receiving user request from client (calling request) I > Capturing the user provided data P Validating the user input 1 Calls the business method to get business services and get processed data > Keep the processed data in memory(request/session/application scope) I > Finally forwarding the request t o VIEW. i '~ IVote: should not write business-Logic/Data-Access-Logic in the Controller Layer. Because that is not reusable Presentation Layer: - I P Receive the control from Controller Layer / P Generate the output by taking the data from memory(request/session/application scope), which is stored by controller layer P Generated output will be given t o web-server, which intern return present the output to browser Business/Service Layer: 1I Naresh i Technologies, Opp. Satyam Theatre, Anleerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 . 2000 Certified CompanyL-- - -.------ ---..--- -. -- -- - -.- -- - .--- -----.- - Page 1 http://javabynataraj.blogspot.com 2
  • 3. . , -.-- . . . - - - L--.-. i -- O Receiving request from Controller Layer 1 P Contacting the Data Access Layer to get the database data 3 Implementing the business logic 3 Return the control/processed-data to Controller Layer PersistentIData-Access Laver: i Receiving the request from business Layer I P Contacting database to get the database data O Return the accessed data to business Layer I Data Laver: 1 > It is a database. - ' Q) What are the different logics available in Enterprise Application? I I Presentation Logic: Logic used to present the output/input. I I Application/Controlling Logic: Logic used t o control the flow of application. II- 1 / Business Logic: Programmatical implementation of business rules is nothing but business logic. jI Data Access Logic: Logic used t o contact the Database. - I Q) What are the Sun Microsystems technologies and frameworks in enterprise application development? Controller Layer 'IServlets I / JSF . ' I Presentation Layer JSP Business Layer t EJB2 session beans EJB3 session beans WIDB(Message Driven Beans) ' WEB-SERVICES Data Access Layer JDBC Ejb2 entity beans Ejb3 entitys[JPA ] (java persistence API) I Q) What are the non-Sun Microsystems technologies and frameworks in enterprise application 1 development? 1 1 Controller Layer struts Spring Web MVC ' I Wicket-- Tapestry 'I Flash I I 1 , 1 Objective of Hibernate: Developing Data access layer of an Enterprise application 1 I Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 II Presentation Layer HTML Velocity Freemarker Flex ~ u s i n e kLa-yer Spring AOP Spring JEE WEB-SERVICES L--. An IS0 9001:2000 Certified Company-..- -- --..-.-- --- - -- -. .-- Page 2 - 1 Data Access Layer Hibernate lbatis Toplink JDO Spring DAO Spring ORM http://javabynataraj.blogspot.com 3
  • 4. , Hibernate-Introduction ' Q) What is persistence in a java based enterprise application? ! I > The process of storing enterprise data in to relational database is Iknown as persistence Q) What is the traditional style of achieving persistence in java based enterprise application? I > Sending SQL statements t o the Database using JDBC API I I I ' Q.) What are the iimitations of the traditional approach? I 'i Application portability to the Database is lost (Vendor lock: diff SQL statement for the db's) 1 3 Mismatches between Object oriented data representation and relat~onaldata representation are not I I properly addressed II 3 Requires the extensive knowledge of DB I P Manual operations on Resultset I 7 I I v For every problem while commun~catingwith the database (us~ngJDBC), it throws same I - I exception(java.sql.SQLException). As SQLException is checked exception, so we must write code in try- ;I catch block or throws has to be specified. , I I I > Need to implement caching manually iI I 3 In the Enterprise applications, the data flow with in an application from class to class will be in the 1 form of objects, but while storing data finally in a database using JDBC then that object will be I converted into text. Because JDBC doesn't transfer objects directly. I 'I 1 4.)what is an alternative for traditional approach? ! / > ORM (Object Relational mapping) I > It is technique of mapping objected oriented data to that of relational data > Through ORM technique persistence services (database) are provided to business layer in pure object oriented manner by overcoming all limitations of the traditional approach II Q.) What is Hibernate? & Hibernate is an ORM implementation > Hibernate is an Open source i ! b Hibernate is a framework I > Hibernate invented by Gavin King. He also invented JBoss server and JPA - Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An I S 0 9001 :2000 Certified Company- -- I Page 3 http://javabynataraj.blogspot.com 4
  • 5. ~ ~ ~ ~ ~~ ~. ~-~ . ~ ~ ~~ .~~~ . Hibernate-Introduction -----. ---._-_.. "..._._..._Ul--- Mr.SekharReddy..-. - ,,?--,.->>"< 3 Hibernate is a non-invasive framework, means it won't forces the programmers to extend/implement arly class/interface, and in hibernate we have all POJO classes so its light weight k Hibernate can run with or without server, I mean it will suitable for all types of applications (desktop or web applications) Q.) What is a framework? A frameworl<is reusable semi finished application that can be customized to develop a specific application. Q.)What are the features of hibernate? 1 9 Hibernate persists java objects into database (Instead of primitives) 9 It provides Database services in Database vendor independent Manner, so that java applications II become portable across the multiple databases I i 9 Hibernate generates efficient queries for java application to communicate with Database i I , 9 It provides fine-grained exception handling mechanism. In hibernate we only have Un-checked I exceptions, so no need to write try, catch, or no need to write throws (In hibernate we have .- the translator which converts checked t o Un-checked) 1 3 it supports synchronization between in-memory java objects and relational records I > Hibernate provides implicit connection pooling mechanism ! I j Hibernate supports Inheritance, Associations, Collections I 3 Hibernate supports a special query language(HQL) which is Database vendor independent 1 9 Hibernate has capability t o generate primary keys automatically while we are storing the records into / database i 1 > Hibernate addresses the mismatches between java and database 11 > Hibernate provides automatic change detection I I I 9 Hibernate often reduces the amount of code needed t o be written, so it lrnproves the productivity II i > Database objects (tables, views, procedures, cursors, functions ...etc) name changes will not affect I I I hibernate code i I > Supports over 30 dialects Hibernate provides caching mechanism for efficient data retrieval I- - > Lazy loading concept is also included in hibernate so you can easily load objects on start up time 1 > Getting pagination in hibernate is quite simple. ( > Hibernate Supports automatic versioning of rows i I I I Nareshi Technologies,Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i An IS0 9001 :2000 Certified Company I 1 - - -. ..--. - -. I Page 4http://javabynataraj.blogspot.com 5
  • 6. Hibernate-Introduction- --- -- McSekharReddy-.- I - - i i 3 Hibernate provides transactional capabilities that can work with both stand-alone or java Transaction 1I 1 API (JTA)imple~nentations...etc . . , II i Hibernate supports annotations, apart from XML I I I , Q.)What are the disadvantages of hibernate? 1II 3 Since hibernate generates lots of SQL statements at runtime so it is slower than pure JDBC i i. Hibernate is not much flexible in case of composite mapping. This is not disadvantage since 1 understanding of conlposite mapping is complex / P Hibernate does not support some type of queries which are supported by JDBC 1 9 Boilerplate code issue, actually we need to write same code in several files in the same application, I ', but spring eliminated this I I 1 1 HibernateArchitecture 1 java application nAL' Hibernate API +r---- I--- Hilreinale Engin e .- configuration file ,I D E C './ Data base 1 Java Application makes use of hibernate API methods calls to inform the persistent needs t o I-,hibernate. Then Hibernate engine generate .lDBC code that corresponds t o the underlying DB by using 1l- mapping file and configuration file information. I I I I r. We can also find the architecture diagrams as follows ... i I i Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1( 1 L.- __ - __-- An IS0 9001 : 2000 Certified Company I .--- .- - - Page 5http://javabynataraj.blogspot.com 6
  • 7. . . . . . . . . . . . . .-. . . . . . . . JTA J N D l . ~ f ...r...*.-...... &..>**..&..."..,."*"? ... *..-.-...'*..." -................. I I -- I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i An IS0 9001 :2000 Certified Com~anv I Page 6http://javabynataraj.blogspot.com 7
  • 8. 2 . / 3 . < c l a s s name="Entlty c l a s s namev t a b l e = " t a b l e name I n d a t & a s e l ' > 1 4 . < l d name="ld v a r l a b l e name" column="prlmary column name l n d a t a b a s e " /> 1 5 . < p r o p e r t y name="variablel name1' column="column name l n d a t a b a s e " /> 1 6 . < p r o p e r t y name=I1varlable2 name" column="column name l n d a t a b a s e " /> ' 7 . < / c l a s s > I 8 . , 9 . </hibernate-rnapplng> Syntax Of Mapping Annotations: 1. @ E n t i t y 2 . @Table(name= " t a b l e name i n d a t a b a s e " ) 3 . p u b l i c class EntityName { 4 . @ Id 5 . @Column(name= "primary column name i n d a t a b a s e " ) 6 . p r i v a t e i n t idVariableName; 7 . 8 . @Column(name = "column name i n d a t a b a s e ") 9 . p r i v a t e S t r i n g variableName1; 1 0 . @Column(nams= "column name i n d a t a b a s e ") 11. p r i v a t e S t r i n g variableName2; 1 2 . / / setters & g e t t e r s 13. 1 Q.) What is hibernate configuration file? i It is an XML file in which database connection details (username, password, url, driver class name) and , Hibernate Properties(dialect, show-sql, second-level-cache ...etc) and Mapping file name(s) are t specified to the hibernate I > Hibernate uses this file to establish connection to the particular database server I i 1 Z Standard for this file is <hibernate.cfg.xml> 3 We must create one configuration file for each database we are going t o use, suppose if we want to 1 ij connect w ~ t h2 databases, like Oracle, MySql, then we must create 2 configuration files. I No. of databases we are using = That many number of configuration files I I I > We can write this configuration in 2 ways... o XML file o Properties file(o1d style) ( > We don't have annotations t o write configuration details. Actually in hibernate l.x, 2.x we defined this j., 1 configuration by using .properties file, but from 3.x XML came into picture. XNlL files are I I always recommended t o use. Syntax Of Configuration xml: 1. < h i b e r n a t e - c o n f i g u r a t i o n > 2 . < s e s s i o n - f a c t o r y > 3. 4 . < ! - - R e l a t e d t o t h e c o n n e c t i o n START --> I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 - ~- - An IS0 9001 :2000 Certified Company ~Tge8-http://javabynataraj.blogspot.com 8
  • 9. I Q.) What is hibernate mappingfile? ' 3 In this f ~ l ehibernate application developer specify the mapping from entity class name to table name i 1 and entity properties names to table column names. i.e. mapping object oriented data to relational data is done in this f ~ l e I i Z Standard name for this file is <domain-object-name.hbm.xml> I I I r In general, for each domain object we create one mapping file Number of Entity classes = that many number of mapping xmls I Z Mapping can be done using annotations also. If we use annotations for mapping then we no need to I write mapping file. I Z From hibernate 3.x version on wards it provides support for annotation, So mapping can be done in two ways o XML o Annotations Syntax Of Mapping xml: 1 1. <hibernate-napping> i I Nareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001:2000 Certified Company http://javabynataraj.blogspot.com 9
  • 10. 5. <property name="connection.driver~~1a~s'~>DriverClass Name </property> 6 . <property name="connection.url">URL </property> 7 . <property name="connection.user">user </property> 8 . <property name="connection.password~l>pa~~~~rd</property~ 9. < ! - - Related to the connection END --> 10. 11. < ! - - Related to hibernate properties START --> 1 2 . <property name="show-sqll'>true/false</property> 1 3 . <property name="dialettt>Databasedialet class</property> 14 . <property name="hbm2ddl.auto">create/update or what ever</property> 15. < ! - - Related to hibernate properties END--> 16. 17. < ! - - Related to mapping START--> 1 8 . <mapping resource="hbm file 1 name .xml" / > 19. <mapping resource="hbm file 2 name .xml" / > 20. < ! - - Related to the mapping END --> 21. 22 . </session-factory> 23 . </hibernate-configuration> I ' Q.) What are the Simple Hibernate Application Requirements? I -. Setting hibernate environment I I I 1 1 Entity class 2. Mappingfile(Requiredif you are not using annotations) i 3. Configuration file 1 i ;To work with hibernate framework we need to add .jar(s) files provided by that framework to ' I I j our java application. 4. DAO class (Wherewe write our logic to work with database) ( 1 i No framework-is installable software, it means we doesn't contain any setup.exe I 'i When we download any framework, we will get a 'zip' file and we need to unzip it, to get the required 1.i jar files, actually all frameworks will follow same common principles like... 1 j ! o Framework will be in the form of a-setof jar files, where one jar file acts as main (We can call ! this file as core) and remaining will acts as dependent jar files. 1 I o Each Framework contain at least one configuration xml file, but multiple configuration files also iallowed. > We can download hibernate jar files from the following links. Based on requirement we can download the corresponding version. o For version 2.x (http://sourceforge.net/projects/hibernate/files/hibernate2/) o For version 3.x (http://sourceforge.net/proiects/hibernate/f1les/hibernate3/) o For version 4.x (http://sourceforge.net/projects/hibernate/f1Ies/hibernate4/) > While dowr~loadingselect .zip file for windows environment, select .tar flle for unix environment. 1 j Naresh iTechnologies,Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001:2000 CertifiedCompany 1:I - --- Page 9 1http://javabynataraj.blogspot.com 10
  • 11. -- Hibernate-Introduction After downloading the zip file, unzip it and we can find the required jars in the extracted folder. If we consider 4.x version, we need the following jars to work with hibernate application. NOTE:Along with the hibernate jars we must include one more jar file, which is nothing but related to our database, this , is depending on your database. For example, if we are working with Oracle we need to add ojdbc6.jar. 4.) What are the Steps t o develop hibernate applications?- 1 ' Step 1: Develop persistent/domain/entity class for each table of the relational model - Step 2: For each entity develop a mapping file i Step 3: Develop the configuration file I Step 4: Add hibernate framework jar files in the classpath 1 / Step 5: Make use of hibernate API and perform persistent operations 4.) H o w t o Make use o f hibernate API t o perform persistent'operations? I STEP1: Create Configuration object Configuration configuration = new Configuration(); STEP2: Read configuration f ~ l ealong with mapping files using configure() rnethod of Configuration Object I configuration.configure(); 1 S'rEP3: Build a SessionFactory from Configuration I SessionFactory factory = configuration.bhildSessionFactory(); !-STEP4: Get Session from SessionFactory object Session session = factory.openSession(); I STEP5: Perform persistence operations I I 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified Company - -- -- Page 10-http://javabynataraj.blogspot.com 11
  • 12. Hibernate-Introduction The Session interface provides methods to perforni CRUD (Create Read Update Delete) operations o n i,..- I the instances of mapped entity classes. Perform transactions if require while performing DML: :I operations. Session interface methods are... I L; S s;,0 1-1 2:a:..'*i :3 : - l!l.:.el-tincl okjelzt .8' intl:~database. ! :- . . ses$;it:~n 1.19date1:s:- LJ:.~.cl~!it-~ciobject ' sit1 the ~:latabase I , STEP6: Close the session I Final .flow will be... Sa:ssiul-1 TI-ansaction Close Statet?lents ~areshi Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666, 23734842 An I S 0 9001 :2000 Certified Company-- . . Page 11http://javabynataraj.blogspot.com 12
  • 13. Hibernate-CRUD Application- By Mr. SeltharRedcly--.. - . ' - A 4.) Develop Hibernate application, i n which w e can perform account creation, retrieve, update and delete? SQL Script CREATE TABLE ACCOLIkIT ( ACCNO NUMBER (5) IUOT NULL, NAME VARCHAR2 (20) NOT NULL, BAL NUMBER(8,2) NOT NULL, CREATION-DT DATE NOT NULL, PRIMARY KEY ( ACCNO ) 1 i ACCOUNT TABLE E::-'..L CREAT IOII-DT fiP541.07J ':74>:7illiJ . -..- . ! 91:1U02 yellari.diis; E:i;5d$.69 5;'15;21:112 gDlli13 clierr-,! - -ac(-iS?.?6 5,,'2!2l:l12 I I hibernate.cfg.xml 1 1. <?xml version='l.O1 encoding='UTF-8'?> 2 . <!DOCTYPE hibernate-configuration PUBLIC I 3. "-//Hibernate/Hibernate Configuration DTD 3.0//ENM 4 . "http:/>hibernate.sourceforge.net/hibernate-configuration-3.0.dtdIT> --- -- I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I I I An IS0 9001 :2000 Certified Company ---- - p a s -http://javabynataraj.blogspot.com 13
  • 14. , . - ~ . .- -~ ~ - .. . .. - - ~ ~.~ ~ ~~ ~ . . .~~ I - : Hibernate-CRUD--Application.... -. ..-. .. . . ------. - ,-&c3 . "< . By Mr. SekharReddy -;-- --.-...... . -..--.. .-----.--.-. ---.yr*r- -.,..YLTu_,- --- . I .% ,.: j 1 4 . < / p r o p e r t y > ! 15. ,,./ :, .,.- ., . . ~" -. .. ,. . - y ,;...!-:-- -.-.!!~;.c:ion. u s e r n a m e " > s y s t i : n ~ < : p r o p ~ r ~ ~ - > j 1 6 . <propert;. ::!I:!?-" ::ci!!.!?c:?.on. passiiord">tiqer<ipropert;.:- 1 1 7 . <prop?rt:;: n :;:I.-2-"<::.::!?i:?ction.d r i v e r-c l a s s "> j 18. G : ?z.:.e.:.;:::. : ! r i v e r . O r a c l s D r i ~ r e ~ I 1 9 . ',i ~ J L ~ . , , ~ :i;; ; 2 0 . - .>,%73, - ;-. . - - -. t c , - . - - . .. : .!iection.pool s i z e n > l5.., i-,rpei:t;::- 1 2 1 . ;Proper ::..,. ,; -..,..= "::.:I::.: -. s c l l " > t r u e < / p r o p e r t . - 2 2 . < ,-,=.-- .. ,, -;,. -:!' .-,. ..,?-I,-! 12:. .. - '. . . . . . ... .. .. ...< . autoU>update</pr-i>;..sr~;:;:, i 2 3 . <propert,- r~,-.;-e="us.=--s q l - c o r n m e n t s " > t r ~ e < / p r ~ ~ ~ p e r t ~ . ~ > 1 2 4 . <propert;- l > , : : > ~ = ~ !~..-.n-.tI:...-. -sqll'>true</proper-c;.:. i 2 5 . <~nappLngre~~~ur~:~="c~~m/sekharit/hibsrnate/mappitig/Ar-cc~ur:t . 1 2 6 . </session-factor;-:. 1 27. I i 28. </hibernate-configura:~311:. j 2 9 . I j SessionUtil.iava 1, package corn.sekharit.hibernate.ur;il; 1 2. 3. import org.hibernate.Session; 1 4. import org.hibernate.cfg.Configuration; 1 5. 1 6. public class SessionUtil { 1 7. 1 8. private static final ThreadLocaI<Session>threadLocaI = new ThreadLocaI<Session>(); I 9. private static org.hibernate.SessionFactory sessionFactory; ! 10. , . , 11. static { i j 12. try { . . sessionFactory = new Configuration().configure( 1- I ::: "com/sekharit/hibernate/config/hibernate.cfg.xmI").buildSessionFactory(); - .1. . } catch (Exception e) { 1 iii e.printStackTrace(); Ir 1 18, } 1j 1 19. 1 20. private Sessionutilo { I 21. } I 1 22. I 23. public static Session getThreadLocalSession() { 24. Session session = (Session)threadLocal.get(); 25. II 26. if (session == null) { 27. session = sessionFactory.openSession(); j_11 28. threadLocaI.set(session); ! 29. } ! 30. ! :;: } . return session; 1:, I 1 33. ?I I 34. public static void closeThreadLocaISession() { ! ! I 'I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I !, ! An I S 0 9001 : 2000 Certified Company I Page 2http://javabynataraj.blogspot.com 14
  • 15. -~-- -.- .- - - . ~ - ~~~. . - -- --- - Hibernate-CRUD Application By Mr. ~ e l t l ~ a r ~ e d d ~ Session session = (Session)threadLocal.get(); tlireadLocal.set(nulI); if (session != null) { session.close(); 1 1 public static Session getsession() ( return ses~ionFactory.openSession(); 1 public stat~cvoid closeSession(Sessionsession) { if (session != null) { session.close(); 1 1 -- , Account.java I 1. package com.sekharit.hibernate.bean; - 2. / 3. import java.ut~l.Date; 4. 1 5. public class Account { 6. private long accno; 1 7. private Str~ngname; 8. private double balance; I 9. private Date creat~onDate; 10. , 11. public long getAccno() { return accno; 1 public void setAccno(long accno) { this.accno = accno; 1 public String getName() { return name; 1 public void setName(String name) { 24. this.narne = name; I 25. ) 26. 1 27, public double getBalance() { I 28. return balance; I 29. 1 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I An IS0 9001 :2000 Certified Company I page~---'http://javabynataraj.blogspot.com 15
  • 16. [--? -- . .- - - - - - . . -- .-- - .- ~ ..- . ~~ , -.. - I Hibernate-CRUD Application ! -- - --- --- -... .. . -. . .--... .-.yl.S..-- By Mr. ~ e k h a r ~ e d d ~- - - - ~ .< ,.. ,----.U .- 1 30. 31. public void serBalance(double balance) { 1 32. this.balance = bala~ce; ! 33. 1 35. public Date getCreationDate0 { return creationDate; 37. } I 38. 1 39. public void setCreationDate(Date creationDate) { 40. this.cr?ationDate = creationDate; 41. } 1 42. 43. @Override 1 44. public String tostring() { 1 45. return "Account [accno='! t accno + ",balance=" + balance 46. + ", creationDate=" + creationDate + ",name=" + name + "I"; 47. } 1 48. I Account. hbm.xml 1. <?xml version="l.O" encoding="UTF-8"?> 2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.O//ENU / 3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > 1 4. <hibernate-mapping schema="SYSTEM" > 1 5. <class name="com.sekharit.hibernate.bean.Account"table="ACCOUNT"> <id name="accno" type="longU> <column name="ACCNOUlength="SUnot-null="true" ></column> </id> <property name="nameUtype="stringM > 10. <column name="IUAMEUlength="2OVnot-null="trueV></column> 11. </property> 12. <property name="balanceUtype="doubleU > 13. <column name="BALNprecision="8" scale="2" not-null="trueN></column? 14. </property> 15. <property name="creationDate" type="dateM> 16. <column name="CREATION-DT" not-nllll="true" ></column> 17. </property> 18. </class> 19. </hibernate-mapping> AccountDAO.iava 1. package com.sekharit.hibernate.da0; ,2. 3. import 0rg.hibernate.HibernateException; 4. import org.hibernate.Session; 5. import 0rg.hibernate.Transaction; 1 ::import com.sekharit.hibernate.bean.Account; 1 8. import com.sekharit hibernate.util.5essionUtil; llaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 --- An I S 0 9001 :2000 Certified Company ---.- --- - Page 4http://javabynataraj.blogspot.com 16
  • 17. - - Hi..-bernate-CRUD Application. By Mr. SeltharReddywi.e-ii-ii-l--- 9. 10. pcrbl~cclass AccountDAO { 3 1. (~ubllcAccount get(long accno) { 12. 13. Sess1011session = null; , 14. Account account = null; 15. try { I 16. session = SessionUtil.getSess~on(); I 17. account = (Account) session.get(Account.class, accno); , 18. } catch (HibernateException e) { I 19. e.printStackTrace(); 20. } f~nally{ 1 21. SessionUtil.closeSession(session); 22. 1 1 23. 24. return account; j 25. } 26. 27. publ~cv o ~ d~nsert(Accountaccount) { i28. 1 29. Session session = null; I 30. try { 731. session = SessionUtll.getSession(); I 32. session.getTransaction().begin(); 33. session.save(account); 1 34. session.getTransaction().cornm~t(); 35. } catch (HibernateException e) { 1 36. session.getTransaction().rolIback(); 37. e printStackTrace0; 1 38. } f~nally{ 39. SessionUtil.cl~seSession(session); 1 40. } I 41. } 42. I 43. publ~cvoid update(Acc0unt account) { 44. Session session = null; I 45. try { 46. session = SessionUtil.getSession(); 1 47. sess~on.getTransact~on().beg~n(); 48. session.update(account); 1 49. session.getTransaction().comrnit(); 50. } catch (HibernateException e) { ( 51. session.getTransaction().rollback(); -- 52. e.printStackTrace(); I 53. } f~nally{ 54. SessionUtil.closeSession(session); 55. 1 I 56. } 57. 1 58. public void delete(long accno) { I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -- An IS0 9001 :2000 Certified Company - - PagT5-http://javabynataraj.blogspot.com 17
  • 18. -.-- -.-- - - - -. - -- .-- - . -. .- --- -. - Hibernate-CRUD Application B Mr.Sel<harRecldy-- Session session = null; Tramaction transaction = null; try I session = SessionUtil.getSession(); transaction = session.beginTransaction(); Account account = (Account) session.get(Account.class, accno); session.delete(account); transaction.commit(); } catch (HibernateExceptione) { transaction.rolIback(); e.printStackTrace(); } finally { SessionUtil.closeSession(session); 1 i AccountService.iava 1. package com.seltharit.hibernate.service; I 3. import java.util.Date; 5. import corn.sekharit.hibernate.bean.Account; I 6. import corn.sel~harit.hibernate.dao.AccountDA0; 1 7. / 8. public class Accountservice { 9. public static void main(String[] args) { - I 10. AccountDAO dao = new AccountDAO(); 11. 12. // Retrieve Account 13. Account rAccount = dao.get(90001); 14. Svstern.out,println("Account details ...."); Systern.out.println("Accno : " + rAccount.getAccno()); 1 ::: System.out.println("Name : " + rAccount.getName()); 17. System.out.println("8alance : " + rAccount.getBalance()); 18. Systern.out.println("CreationDate: " + rAccount.getCreationDate()); 1 19. 20. // Create Account 21. Account cAccount = new Account(); 22. cAccount.setAccno(90005); 23. c~ccount.set~ame("sekhar"); 24. cAccount.setBalance(6899); 25. cAccount.setCreationDate(new Date()); 1 26. dao.insert(cAccount); 1 27. System.out.println("Account created successfully"); 28. 29. // Update Account I 30. Account uAccount = new Account(); 31. uAccount.setAccno(90003); 32. uAccount.setName("sekhareddy"); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified Company --- Page 6http://javabynataraj.blogspot.com 18
  • 19. I--, Hibernate-CRUD Application--- -- ---.. . . . . . -- . . . . . . By Mi-.Sel;ha~-Reddy ! 33. uAccount.setBalance(4500); 34. uAccount.setCreationDate(new Date()); 35. dao.update(uAccount); 36. System.out.println("Account updated successfully"); 37. 38. // Delete Account 39. dao.delete(90002); 40. System.out.println("Account is deleted successfully"); 41. 42. } 43. } After Execution ACCOUNT TABLE : ,-*. .? ;;.,-.c c- 1.10 Il.,li.lE E:AL CREhT 101I-UT t I:i.:a>, ?:-eddy 69541.03 5: 29,'21:1!:: 9l:ll:lOj ~e;tllll-edjj' 45i10 j!Z?jLI:l]z !21:11:105 5el:hal- 6Sgg 529jiC112 1 Q.) Rewrite the above application, using annotations instead of mapping file? d . . *' cctn.rtkb~arit.hih~rnatr.utiI :.i. .: Ser-~ian!JtiI,~a~.~a . ., . r-:.:,.-J. JRE S y . ~ t i i i ~L i b r a y ,...;;a::,:. . , - -Hitxrnate 3.3 Annctation': F,t Entit!. I:;lanagel...... i , . Hitlel-nate3.3 Cnre Libraries LI ~ i jRefer~ticedLihrariel: 080 c<clbclJ,jar lib 3 . . ,. 1 hibernate.cfg.xml . . : 1. <?xml version='l.O' encoding='UTF-8'?> 1 2. <!DOCTYPE hibernate-configuration PUBLIC 3 .-- "-//Hibernate/Hibernate Configuration DTD 3.0//ENn 4. "http://hibernate.sourceforge.net/hibernate-configuration-3.O.dtd"~ I 5 . 6. <hibernate-configuration> 8. <session-factory> 9. <property.... /> ............ ! Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company Page Ihttp://javabynataraj.blogspot.com 19
  • 20. ~ . - .. - i1 - Hibernate-CRUD Application By Mi-.Sekhal-lieddy.- -:, -- / -. . -.'%-*au#A&.Lcas* -*=--&= i I ~'-, ; 23. 1 24. ' A ! 25. public void setAccno(1ong accno) { j 26. this.accno = accno; ,, ' 27. } 1 28. I? ! 29. @Column(name= "NAME", nullable = false, length = 20) ,. 30. public String getName() { ,--.. 31. return name; 32. } ! 33. , . I : 34. public void setName(String name) { 1 35. this.name = name; ~. j 36. } ! i 37. I I 38. @Column(name= "BAL", nullable = false, precision=8, scale=2) . I 1 39. public double getBalance() { I ) 40. return balance; 41. } 1/ 1 42. , j I 1 43. public void set~alance(doublebalance) { I 44. this.balance = balance; - 45. } I 1 46. ., I x. 47. @TemporaI(TemporaIType.DATE) I ! I 48. @Column(name= "CREATION-DT", nullable = faise) ,. , 1 49. public Date getSreationDate() { i 50. return creationDate; 1I . 51. } i- 52. 1,h :. 53. public void setCreationDate(Date creationDate).{ ,I* . 54; ! this.creation[>ate = creationDate; 1.- 55. } 56. I i 1 57. @Override 1 58. public String tostring() { 1 59. return "Account [accno=" t accno + ",balance=" + balance 1, 1 60. t ",creationDate=" + creationDate + ",name=" + name + "I"; 61. } l~ i 1 62. , 63. 1 Account.hbm.xml I1: ---NOT REQUIRED--- - I, AccountDAO.java ! I , ---Same As Above--- I - i I AccountService.iava I! ---Same As Above--- 1 ' - / I / r I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 i An I S 0 9001 :2000 Certified Company II -- _ _ _ _ 1 Page 9http://javabynataraj.blogspot.com 20
  • 21. -.- -- - - -. -- -- --- - -- -- -- - ---- - --- - - - - ---- H ibernate-CRUD Application Bv MI-.~ e l t h a r ~ e c l d v - Hibernate - The type Annotationconfiguration is deprecated I I Problem I Working with Hibernate 3.6, noticed the previous "org.hibernate.cfg.Annotat~onConf~gu~-at~on",1s marked as "deprecated". Code snippets ... org.hibernate.cfg.AnnotationConfiguration; private static SessionFactory buildSessionFactory() { try 1 return new AnnotationConfiguration().configure().buildSessionFactory(); 1 } catch (Throwableex) { The code is still working, just keep displaying the deprecated warning message, is there any replacement for I "AnnotationConfiguration" ? I I ! - I - i Solution System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionlnlnitializerError(ex); 1 . I Q In Hibernate 3.6, "org.hibernate.cfg AnnotationConfigurat~on"is deprecated, and all its functiona!~tyhas been ! moved to "org.hibernate.cfg.Conf~gurat~on". I 4 SO, you can safely replace your "AnnotationConfiguration" with "Configuration1' class. I Code s n i ~ ~ e t s... import org.hibernate.cfg.Configuration; ! /I... System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionlnlnitializerError(ex); 1 I 1 I I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company Page 10 private static SessionFactory buildSessionFactory(){ try 1 return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { http://javabynataraj.blogspot.com 21
  • 22. -- .- - - - - -- - - - _-- _ __ .,, Hibernate-CRUD Application-.-___a By Mr.SeltharRedciy- -- ---.-----. -'-4- I A Account" /> SessionUtil.java . . 1. package com.sekharit.hibernate.uti1; I ," - ' 2, import org.hibernate.Session; 3. import org.hibernate.cfg.AnnotationConfiguration; ,i. 4. public class SessionUtil { % . I 5. I ,' 6. private static final ThreadLocal<Session> threadLocal = new ThreadLocaI<Session>(); 7. private static org.hibernate.SessionFactory sessionFactory; 8. , I 9. static { I' 10. try { ! 11. sessionFactory = new AnnoationConfiguration().configure( : 12. "com/sekharit/hibernate/config/hibernate.cfg.xmI").buildSessionFactory(); -:I, 13. } catch (Exception e) { I 14. e.printStackTrace(); ," 15. } - 1 16. } I I , 1 17. ........................... 1 18. ........................... r Account.iava 1. package com.sekharit.hibernate.bean; 2. 3. import-java.util.Date; 4. 5. import javax.persistence.Column; I 6. import javax.persistence.Entity; 1 7. importjavax.persistence.ld; I 8. importjavau.persistence.Table; 1 9. import javax.persistence.Tempora1; ' 10. import javax.persistence.TemporalType; i 11. @Entity 1 12. @Table(name="ACCOUIVT") . 1 13. public class Account { 1 14. private long accno; 15. private String name; 16. private double balance; 17. private Date creationDate; 18. ' 1 9 . @Id 20. @Column(name= "ACCNO", nullable =true, length=5) 21. public long getAccno() { 122. return accno; Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company. . . . . . . . . .- . . . . . . . . . . . . . . . . . . . - .... - -..- .-- --. ~a ge8.'http://javabynataraj.blogspot.com 22
  • 23. ' ' Hibernate-Arcl~itect~~ralElements , Q.) Explain more about hibernate.cfg.xml (configuration file)? I I . 3 This xml file used to specify locations of mapping files/Entities I > In projects we don't give the database details(ur1, username, password, driverclass) in the I configuration file, instead of that, we give JNDl name of DatatSource. <property name="connection.datasource"~myDataSourceIlame~/property~ I 9 Hibernate slupports default connection pooling but which will not be used in projects We use always 1 server provided connection pooling. I I) connection.pool-size: Used to configure hibernate provided connection pooling in hibernate.cfg.xml : I I I 2) show-sql: if the 'show-sql' value is true we can view all the hibernate generated queries in the I console. <property name="show~sql"~true~/property~ I -- 3) use-sql-comments :To add SQL comment t o the SQL query generated by Hibernate I <property name=" use~sql~comments">true~/property~ I - 1 4) format-sql : Format the SQL ql;ery, so that easy to read <property name format-sqln>true</property> 5) hbm2ddl.auto: It has two values I a. create or create-drop b. update I a,) Create: If its value is create while running the application ! Case 1:table does not exist i Create new schema based on the mapping file configurations i Case 2: table exists Drop the existing schema and create a new schema based on the mapping file configurations I b.) Update: If its value is update while running the application I Case 1:table doesn't exist Create a new schema based on the mapping file configura.tions I Case 2 :table exists- i Use the existing schema 1 > If its value is 'create' while running the application hibernate will drop the old schema and it will I create the new schema. (Based on HBlVl file) I NareshiTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -. --- An IS0 9001 :2000 Certified Company------- P a g e 1http://javabynataraj.blogspot.com 23
  • 24. I 3 If its value is 'update', hibernate will check for schema existence. If schema doesn't exist it will I I create the new schema. If the schema already exists it uses the existing schema for persistence operations. Q.) What do you know about dialect in Hibernate? P Dialect class is a simple java class, which contains mapping betweerr java language data type and database data type. i / P Dialect class contains queries format for predefined hibernate methods I 2 Hibernate generates queries for the specific database based on the Dialect class. If you want t o shift 1 from one database to another just change the Dialect class name in hibernate.cfg.xml file. 1 I 1 9 All Dialect classes must extend 'Dialect' (abstract) class i ! 1 9 Hibernate supports almost 30 dialect classes. 9 If we want we can write our own dialect by extending Dialect class I I Dialect class is used convert HQL queries into database specific queries. I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An IS0 9001 : 2000 Certified Company I .--- - - -- -1 Page 2http://javabynataraj.blogspot.com 24
  • 25. Hibernate-Arcl~itecturalElements I MySQL with InnoDB 1 org.hibernate.dialect.MySQL5lnnoDialect DB2 AS1400 DB2 05390 PostgreSQL 1 MySQL I I Oracle (any version) org.hibernate.dialect.Oracle8iDialect I - org.hibernate.dialect.DB2400Dialect org.hibernate.dialect.DB2390Dialect org.hibernate.dialect.PostgreSQLDialect org.hibernate.dialect.MySQL5Dialect 1 Sybase 1 org.hibernate.dialect.SybaseDialect ' oracle 9i 1 1 oracle l o g org.hibernate.dialect.Oracle9;Dialect org.hibernate.dialect.Oracle10gDialect 1 I Microsoft SQL Server / org.hibern;te.dialect.~~~server~ialect '/ >Sybase Anywhere TI Microsoft SQL Server 2008 I org.hibernate.dialect.SQLServer2008Dialect I I I org.hibernate.dialect.SybaseAnywhereDialect 1 I I I SAP DB 1 org.hibernate.dialect.SAPDBDialect , 8 ! I I HypersonicSQL 1 org.hibernate.dialect.HSQLDialect 1 1 I I -I I I lngres Mckoi SQL -1 I I org.hibernate.dialect.MckoiDialect I org. hibernate.dialect.lngresDialect org.hibernate.dialect.ProgressDialect1 I I Q.) Explain more about Hibernate mapping file? I I Progress I lnterbase FrontBase 1 / Firebird > Each hibernate mapping file must contain only one <id> (or relevant tag <composite-id>) > Java object identified uniquely by the <id> tag property. org.hibernate.dialect.lnterbaseDialect 1 ! i org.hibernate.dialect.FrontbaseDialect org.hibernate.dialect.FirebirdDialect ..A I > <id> tag property corresponding column can be primary key or non-primary key in the database org.hibernate.dialect.PointbaseDialectPointbase I I > In mapping file class names and property names are case sensitive. But Table names and column I I I names are not case sensitive. ! 1 1 I Nareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 ! An IS0 9001 : 2000 Certified Company-- PTe- 2-...- http://javabynataraj.blogspot.com 25
  • 26. , ~ ~~ . - ~ ~ . .~ ~ . ~ ~ ' , Hibernate-Architectul-a1Elementsj -~. . . . . . . . -- Mr.SekharRecidy-La,D . - . i - I Ii P When the property name and column name both are same we no need t o give 'column' attribute :,- r When the Pers~stentclass name and table name both are same we no need to give 'table' attr~bute r Generally we write one mapping f ~ l eper one domain object. But it allows writing multiple objects - mapping information within the same mapping file. Per each class mapping we need to write one <class> tag. I r Databases have different ways to organize its tables. Some database places all tables in a different "schemas", some database places all tables in a different "catalogs". If we want we can specify this in <class> tag of the mapping file i 9 In mapping file we write fully qualified name of the entity class in "name" attribute of <class> tag. Instead of that we can write package name separately using "package" attribute of <hibernate- mapping> tag P In the mapping file we no need t o map all the properties of the entity and all the columns of table. As per our requirement we configure required properties of the entity and columns of the table 1 Q.) Explain about annotations which are used in our application t o map entity t o table? I P In our examples if we observe, we used the following annotations II o @Column---we---- I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified Company Page 4http://javabynataraj.blogspot.com 26
  • 27. ~ pppp-.- ..... . . Hibernate-AI-chitecturalElements .......................8 _nl..x&r ... -~.. , . . I ~ r . ~ e k l ~ a i - ~ e c l d y--. - - o @GeneratedValue o @Temporal /- All the above annotations we are taking from java.persistence package. Actually this paclcage is not the part of hibernate API. This paclcage is from .IPA(Java Persistence API). > These annotations also given by hibernate. But we don't prefer to use hibernate given annotations. We prefer t o use .lPA annotations. Reason for this is, Hibernate is a specific API, where as ]PA is a specification. If we use JPA annotations we have to flexibility to change the implementation vendor without changing application code. i > .IPA is an APl(from SUN), its not the implementation. There are multiple implementations are there for ]PA. Some of famous implementation of ]PA are Open.lPA, Hibernate, Toplink Essentials, Eclipselinlc ...etc. ' 4.)What is Configuration object? > Object Oriented representation of hibernate configuration file along with mapping file is known as - Configuration object - 3 By default Hibernate reads configuration file with name "hibernate.cfg.xml" which is located in1 "classes" folder I 9 If we want t o change the file name or if we want change the location of "hibernate.cfg.xml" then we need to pass user given configuration file name (along with path) t o "configure()" method of 1 Configuration class 1 P Configuration object Stores the configuration file data in different variables. Finally all these variables are grouped and create one high level hibernate object called SessionFactory object. I P So Configuration object only meant for creating SessionFactory object I > If we want we can provide the configuration information programmatically, without writing I configuration file.(But it will become Hard coding, so not advisable) 1 Programmatic configuration I Adding mapping files to configuration object programmatically -- Configuration cfg = new Configuration() 1 .addResource("ltem.hbm.xml") .addResource("Bid.hbm.xml"); I - . - Adding Entities(anrl0tated persistent classes) t o configuration object programmatically I Nareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified CompanyI . . . . . . . . . . . Page 5http://javabynataraj.blogspot.com 27
  • 28. -- - - . ~. - ..-~--.. - - -.- . - - -..--- -. --. . -. I Iiibel-nate-AI-chitectul-a1Elements. ----- --- --- - .- -- ..---. . ,- . . . . . - ,.- . - MI-.SekharRectciy 1- ......- ... .~ .- m.JI,X, I ,. , Configuration cfg = new Configuration() .. .addClass(org.hibernate.auction.ltem.class) .addClass(org.hibernate.auction.Bid.class); i i ) To add hibernate properties to Configuration object programn~atically Configuration cfg = new Configuration() .addClass(org.hibernate.auction.ltem.class) .addClass(org.hibernate.auction.Bid.class) .setProperty('hibernate.diaIect", "org.hibernate.dialect.MySQL11~noDBDialect") .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test") .setPr~perty("hibernate.order~updates","true"); This is not the only way to pass configuration properties to Hibernate. Some alternative options include: 1. Pass an instance of java.utiI.Properties t o Configuration.setProperties(). 2. Place a file named hibernate.properties in a root directory of the classpath. 3. set System properties using java -Dproperty=value. 4. Include <property> elements in hibernate.cfg.xm1 (this is discussed later). If you want to get started quickly hibernate.properties is the easiest approach. The org.hibernate.cfg.Configuration is intended as a startup-time object that will be discarded once - aSessionFactory IS created. I Q.) What is SessionFactory? SessionFactory is an interface and SessionFactorylmpl is the implimented class It is factory of Session objects It is heavy weight object that has t o be created only once per application. SessionFactory object provides lightweight Session objects. SessionFactory is not singleton. Lets create it only once using Util/Helper class SessionFactory is a Thread safe object. You need one SessionFactory object per database. So if you are using multiple databases then you would have to create multiple SessionFactory objects. SessionFactoryis also responsiblefor second-levelcaching. Q.) In one appl~catlon,how many SessionFactoryobjects Ican use ? > ASessionFactory is pretty heavyweight, so, we recommend creat~ngone and caching it in a singleton type of way. Then, you can create as many Session objects from it as you like. Q.) Why SessionFactoryis heavy weight? P SessionFactory encapsulates Session objects, Connections, Hibernate-properties, cashing and mappings. - -- - - - - - - - - - - - - -- --- - - - -- -- - - - Naresh i Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 -- An IS0 9001 :2000 Certified Company- - ~ a g e 6 -http://javabynataraj.blogspot.com 28
  • 29. Hibernate-Architectural Elements Q.) What do you know Session object? Session is an interface and Sessionlmpl is implemented class, both are given in orghibernate."; r Session object is called persistent manager for the hibernate application. r It is a single-threaded(not-thread safe), short-lived object > It Wraps a JDBC connection r The Hibernate Session operates using a single JDBC connection which can be injected by the hibernate while constructing session object. I > It has convenience methods to perform persistent operations. r It is a factory for Transaction objects r Holds a mandatory (first-level) cache of persistent objects I Note: After we complete the use of the Sesslon, ~thas to be closed, to release all the resources such as associated objects and wrapped JDBC connection. , 4.)What is Transaction ?- -.. r Transaction used by the application to specify atomic units of work (Transaction management). - i Using Session Object we can create Transaction object in t w o ways. o Transaction transaction =Session.getTransaction(); o Transaction transction = session.beginTransaction(); > Transaction object is unique per session object. > Transaction interface defines following methods to deal with transactions. o transaction.begin() {Transaction beginning) o transaction. commit(); { successful transaction ending ) o transactin.ro!lback(); {un successful transaction ending ) > Default auto commit value is false in Hibernate. r Default auto commit value is true in JDBC 3 In hibernate even to execute one DML operation also we need to implement Transactions. > Hibernate supprots o JDBC Transaction. o jTA Transaction. o Spring Transaction - Sample transaction code is as follows... I - 1. Session = sessionFactory.openSession(); I 2. Transaction t x = null; 3. tv { 4. tx = session.beginTransaction(); I 5. // DML operations 6. tx.commit(); I 7. ) catch(Exceptione) { -1 I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 . ..-..- - ....--..-. ..--.-- .. ...- .. --.-- An IS0 9001 : 2000 Certified Company-- -- Page 7http://javabynataraj.blogspot.com 29
  • 30. 11 Hibernate-Architectural Elements . , Mr.Se1tharRecldy--=A.-- -- s - 1 Q.) Why we have written SessionUtil class? C When some common logic is repeat~ngacross the rnult~pleclasses of an application, ~tIS better to 1 move the common logic into some util class. Where ever we need that common logic we make use of i util class. I ! i I 0 SessionFactory is heavy weight and it's not singleton, so we should make one SessionFactory per 1 database. i i 0 Using Util /Helper class we read the configuration file only once and we create one SesisonFactory . I and we are providing fac~lityto get session object and t o close session object. I / Hibernate complete architecture Read ! !I class i'i.ypl. I configure adatabase driver in eclipse: !: > Launch or open MyEclipse Database Explorer prospective. In the DB Browser window right click on 1 the white place and select "new " option. iL .mEC' .- , C'scatc A TJses i Scssiorl Factor?. I 1 DAI~I~:,SC L<cr,c.i .. -1::. - . - v 1 I / O When we choose the new option, it will launch database driver dialog box. Now we need t o fill the Creates cation 1 /I - - I following options in the dialog box. I ......... _ .... Session / > Select driver template as oracle(thin driver), if we are using oracle database. 3' ...... -- -.. ......... ................ ---...................-.....-.........-... - .-- Give the driver name (logical name, which is used t o refer this configuration) 1I 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I 1 An IS0 9001 :2000 Certified Company Page 8 Jhttp://javabynataraj.blogspot.com 30
  • 31. Hibernate-Architectural E l e i ~ ~ e i ~ t s 3 Give the connection url. I 3 Give the username and password. I > Click on Add Jars button, then se!ect classes.jar file ! I- Click on save password > CIick on finish Hibernate Reverseengineering > Open Myeclipse database explorer prospective. i Select the database driver which we have created and right click on it and select open connection 1i It will display a dialog box. Fill the required username and password. 1I r Select appropriate schema where our tables are stored > Right click on the table and select "hibernate reverse engineering" 'i The above operation will display a dialog box i n that I > we need t o select the "java source folder (src)" > select the java package and click on finish I 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -. An IS0 9001 :2000 Certified Company Page 9http://javabynataraj.blogspot.com 31
  • 32. ; Hibernate-Persiste~~tObject Lifecycle. . ." Mr.SekharReddy -I - - - , - 1 ,, I Persistent Object life cycle 1 Persistent Object has three life cycle states 1. Transient state ! 2. Persistent state I 3. Detached stateI I (-"]new - -.-.-instance : 'L- Transient State --A -- -- I Session.get() I j Session.load() Session.save() ; Session.delete() Session.iterate() ! Session.saveOrUpdate() i Session.uniqueResult() Sc.ssion.persist() arb age collection I 1. B Session.scroll()1 : : Session.merge() i f i 1 I : Session.evict() Session.update()1 ! Session.saveOrUpdate() i : Session.clear() i t Session.merge() ~arbage'collection i : Session.close() 1 Session.lock() I j Session.replicate() ,,(. ' ! /.',. i ; : Detached State , / Persistent state Note: Life cycleobject description Transient state Object associate with session NO IIDetached state I I - 3 Object is associated with session means object reference is available to the session object Object present in the database YES N0 9 Object present in the database means object identifier value is available in database primary key column (Non identifier column values are not matter) YES YES Note: We can find the different diagrams for the persistent object life cycle as follows Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company Page 1http://javabynataraj.blogspot.com 32
  • 33. Hibernate-Persistent Object Lifecycle---.- --. - - -. --.-. MI-.SekharReddy I - I , .--- ,-, ;<;, 2;: . _ ,_.A,.._..- - - r ..--/_/- --__---- !,2;/#; I...,. - ---_-- ,.,,-,.,,::,I!.!,;I;,~~ I'~I.IcI(;I~~ ! ? r a t . ~ ~ ~P I ~by------- I I',., ---- /~,lill,~:i;~i:l~~;)a~(!cl~,2~[l:$?::!, '-I ?PI'~~~IPI'I! IT^^-^.. . - ..--/ .. ,I i'11 lrjl;. 31il.e~' - 1 1, 1 ,A2 .p:#:111r-:--tdL,. .%.., I I '-7r..' I 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 7-4 . --_-----Ada!:ltpd from "Hlt:~prr!atp iij 4:ti:y.i' ; - I /byIBallet' 4G King ,I An IS0 9001 :2000 Certified Company 1Page 2 D~tached http://javabynataraj.blogspot.com 33
  • 34. I .. -- .. .. -- -. --, I Hibernate-Persistent Object Lifecycle -- ~ r . ~ e k h a r ~ e d d T -.I - I _ m _ _ < - w - S % .. . -- ,.- i Transient state: An object is said to be in transient state, when it is not associated with session and not present in data base. Example: Table ACCOUNT 1 ACCNO / NAME / BALANCE 1 1001 kesavareddy 1500 11002 1Sekhar 2 0 0 0 1I I i Application code: 1. Account account = new Account(); 2. account.setAccountld(1003); 3. account.setName("yellareddy"); 1 4. account.set8alance(l500); > In the above example account object is not associated with session and there is no matching record in the ACCOUNT table. So we can say that account object is in transient state. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 -- An IS0 9001 :2000 Certified Company-- -- , Page 3 -- http://javabynataraj.blogspot.com 34
  • 35. ' Hibernate-~ersistel~tObiect Lifecvcle i 3 In this state object is non-transactional. 1.e. object is not synchronized with record. 1.e. IVlodifications done to 1 1 entity, doesn't save into database. ( Persistent state: An object is said to be in persistence state, when it is associated with session as well as object present in database. I - ' Example: Table i ACCOUNT ACCNO ( NAME 16iiEF kesavareddy ( 1500' ~ - y1 Sekhar I ' Application code: I Account account = (Account) session.get(Account.class,1002); P In the above example account object is associated with session and there is a matching record in ACCOUNT ! table. So we car: say that account object is in persistent state. I P In this state object is transactional. 1.e.the object is synchronized with database record. I P Changes made to objects in a persistent state are automatically saved to the database without invoking session 1 persistence methods ' USE CASE: Explains Persistent stateI Session session =SessionUtil.getSession(); 1 session.getTransaction()begin(); ! // 'transient' state - Hibernate is NOT aware that it exists Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 :2000 Certified Company -- - Page 4.http://javabynataraj.blogspot.com 35
  • 36. - - - -- -- - - 1 Hibernate-Pel-sistei~tObiect Lifecvcle Mr.SekharReddv 1 / Account account = new Accoui;t(); 1 ! //transition t o the 'persistent' state. Hibernate is N O W 1 // aware of the object and will save it to the database I session.save(account); 1 // modification of the object will automatically be // saved because the object is in the 'persistent'state account.setBalance(500); i // commit the transaction session.getTransaction().co~nrnit(); I USE CASE: Explains Transient state / Session session =SessionUtil.getSession(); sess~on.getTransaction().begin(); 1 // retrieve account with id 1.account is returned in a 'persistentJstate , Account account = (Account)session.get(Account.class, 1); // transition to the 'transientJ state. Hibernate deletes the // database record, and no longer manages the object I session.delete(account); // modification is ignored by Hibernate since it is in the 'transient' state account.setBalance(500); // committhe transaction session.getTransaction().comrnit(); // notice the Java object is still alive, though deleted from the database. // stays alive until developer sets t o null, or goes out of scope I System.out.println(account.getBalance()); Detached state: An object is said to be in detached state, when the object is not associated with session but present in database. Example: Table ACCOUNT I ACCNO I N A M E I BALANCE 1 1001 1kesavareddy / 1 5 0 0 1 I 1002 . / Sekhar 2 0 0 0 II I J Application code : 1. Account account = new Account(); 2. account.setAccountld(1004); 3. account.setName("cherry"); IVaresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 :2000 Certified Company- .- -. --- -- - - - -.- --- -- Page 5 http://javabynataraj.blogspot.com 36
  • 37. Hibernate-Persistent Object Lifecycle -- Mr.Selt11arReddy I L" -- ~~-~~-..----A - 4. account.setBalance(2100); 5. //Now the account object is said to be in transient state 6. session.save(account); 7. // NOLVthe account object is said to be in persistence state . -,- I Session . . . . . . ...... ... .. .................. ........ . . .....> __I iI LOU2 lOUJ - 9. // Now the account object is said to be in detached state. account ......... ................... ...... . .. . .,' . ., - I => In the above example after callingsession.close() method, account object is moved to Detached state from persistent state. As session is garbage collected, if we try t o perform some modifications to entity object those changes will not be / stored into database. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company-- -- Page 6http://javabynataraj.blogspot.com 37
  • 38. - ~ . .~ p-p-p-.-.----..... ~ . -~ ~.-- ..~ .. . . . , Hibernate-Persistent-- -. --- Object Lifecycle Mr.SeltharReddy........ . -... --__.ii_-../i ,-, => In this state object is non-transactional. Means object is not in sync with database. So Changes made to detached ' objects are not saved to the database. -, I i USE CASE: Explains Detached state 1 I , // retrieve account with id 1.account is returned i n a 'persistent' state / Account accoilnt = session.get(Account.class, 1); i // transition to the 'detached' state. Hibernate no longer manages the object I i session.close(); 1 I // modification is ignored by Hibernate since it is in the //'detached1 state, but the account still represents a row in the database account.setBalance(500); i // commit the transaction session.getTransaction().commit(); 1 USE CASE: Explains Detached state / Session session1 =SessionUtil.getSession(); i // retrieve account with id 1.account is returned in a 'persistent' state Account account = sessionl.get(Account.class, 1); I i // transition t o the 'detached' state. Hibernate no longer manages the object I Sessionl.close(); I I // modification is ignored by Hibernate since it is in the //'detached1 state, but the account still represents a row in the database / account.setBalance(500); // re-attach the object to an open session, returning it t o the //'persistent1 state and allowing its changes t o be saved t o the database Session session2 =SessionUtil.getSession(); Session2.getTransaction(). begin(); session2.update(account); I 1 1 // commit the transaction . " j' Saving Changes to the Database r3 Session methods do NOT save changes t o the database - save(); - update(); -- delete(); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 .- An IS0 9001 :2000 Certified Company page-7-http://javabynataraj.blogspot.com 38
  • 39. -- -. ~ -. -.~- . - . - - - .--- :- Hibernate-Persistent Object Lifecycle Mr.Selc11al-Reddy I ..--. .-.-. i a These methods actually SCHEDULE changes to be made to the database Once Transaction committed, all the queries will be pushed to the database - session.getTransaction().commit(); The Persistence Context 4 Each Session object contains one Persistentcontext. It might be containing the follow things: ' Graph of managed persistent instances i List of SQL statements t o send to the database i I ' ~ l u s h i n gthe Context ,! Submits the stoied SQL statements t o the database Occurs when: , - transaction.commit() is called 1 - session.flush() is called explicitly 1 USE CASE :Scheduled Changes Session session =SessionUtil.getSession(); ( Session.getTransaction().begin(); // 'transient' state - Hibernate is NOT aware that it exists Account account = new Account(); //Transition t o the 'persistent' state. Hibernate is NOW // aware o f the object and //schedules the insert statements t o create the object in the database session.save (account); // modification of the object will automatically be saved scheduled //because the object is in the 'persistent' state // (actually alters the initial insert statement since it hasn't been sent yet) account .setBalance(500); I //flushes changes t o the database and commit the transaction session.getTransaction().commit(); 1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 - An IS0 9001 :2000 Certified Company rage trhttp://javabynataraj.blogspot.com 39
  • 40. ---..- - - -. -- --- -.- I H [be1nate-Session Methods Mr.SeltharReddv - i I Session m e t h o d s 1 28. } i : public void setName(String name) { 1 31. this.name = name; 1 I a m going to use the following entity to explain the session methods. ; 1, 9ackage corn.sekharit.hibernate.entity; ! , 2. j 3. import javax.persistence.Column; , 4. ~lnpoitjavax.pers~stence.Entity; I i 5. import javax.persistence.ld; 1 6. import javax.persistence.Table; ! 7. 1 8. @Entity 9. @Table(name= "ACCOUNT") 1 10. p~tblicclass Account ( 11. private int accountld; I 12. private String name; 1 13. private double balance; i 14. @Column(name= "BALANCE") public double getBalance() { return balance; I , public void setBalance(double balance) ( this.balance = balance; 1 ' 15. @Id 16. @Column(name = "ACCNO") 17. public int getAccountld() ( 18. return accountld; 19. } 20. @Override public String tostring() { return "Account [accountld=" t accountld t ",name=" t name t ",balance=" t balance t "I"; public void setAccountld(int accountld) ( this.accountld = accountld; 25. @Column(name= "NAME") 1 26. public String getName()( , 27. return name; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified Company 1: - Page 1http://javabynataraj.blogspot.com 40
  • 41. 4.)What are the differences between load() and get() methods? Hibernate Session provides two method to access object e.g. session.get() and session.load().Both looked quite similar to each other but there are many differences between load and get method which can affect performance of our application. 1.) Throws "org.hibernate.0bjectNotFoundException' if object is not found in cache as well as on database. :Type hierarchy of 'org.hibernate.(3bjectNotFounilExcepti~ri': -> As we can see the ObjectNotFoundException hierarchy, we can say this is un-checked exception..... So we no need to write try-catch block t o handle this exception. - / 2) It is lazy loading, rrieans when we call session.load(Class, identifier) method it will not return entity object, it will, return proxy object. When we try to access the non-identifier properties from the proxy object, at that time it will hit 1 i the database and load the entity object. i 3) As Session.load()return proxy instance, so it is not fully available in any future detached state. I 4) Use this method if it is sure that the objects exist. 5) It is just like EntityManager.getReference0 method of .lPA i I 1)It will return 'null'value, if object is not found on cache as well as on database. I 2) It is early loading, Means when we call session.load(Class, identifier) method it will hit the database immediately and i load entity object and return entity object. I 3) As Session.get() returns a fully initialized instance, so it is fully available in any future detached state. I , 4) Use this method if it is not s u e that the objects exist. II 5 ) It is just like EntityManager.find()method of JPA 1 ' NOTE: If working with detached objects is not needed, load() or getReference() can be used to have better 1 performance. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company Page 2http://javabynataraj.blogspot.com 41
  • 42. Hi bei-nate-Session Methods -, I NOTE: Session.load() or EntityManager.getReference() should be used if a fully initialized instance is not needed, which I , saves a database roundtrip if nothing other than creation of an association is done, with the proxied instance in -- rnailaged state NOTE: load() method exists prior t o get() method which is added on user request. .', 4.)HOW to call get and load methods ? : 50. public void callload(){ 51. Session session = SessionUtil.getSession(); j _ 52. session.beginTransaction(); 53. try { i 1 54. Account account = (Account)session.load(Account.class,9001); 1 55. / / ~ tthis line put Break.point ...Now observe the console, After this line executed, iI 56. //we can't find any select statement. And if observe on the variables window, account object not initialized. ' 57. // Now account isjust a proxy object. ! 58. i 1 59. System.out.println(account.getName()); I 60. //After this line yo" can find select query on the console, And now account object is initialized with database data. 11 61. ( . 62. } catch (ObjectNotFoundException e) { 1 // System.out.println(account.getName{)); //This would fail!!! publicvoid callGet() { Sessionsession = SessionUtil.getSession(); session.beginTransaction0; Account account = (Account) session.gct(Account.class,9001); // At this line put ~ r e a k.p'oint... Now observe the console, After this line executed, //we can find select statement. And if observe on the variables window, //account object initialized with database data // System.out.println(account.getName()); // no problem!!! W h e n t o use Session ~ e t 0and load0 i n Hibernate 1.if object present we have t o implement some logic, if not we need t o implement some other logic. I get(): if the object is not there, it returns null. Then we can implement above requirement as follows Iif(object == null){ //some code I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 L-- -- - -- An IS0 9001 : 2000 Certified Company IJ - Page 3http://javabynataraj.blogspot.com 42
  • 43. ~ ~ ~p p~ - .... .- . . Hibernate-Session Methods Mi-.Sel<hai-Reddy ! //some other code I I load(): if the object is not there it throws an exception. So we can't implement this requirerne~itusing load() For the above requirement we go for get() method. 2. If you we want to use the JavaBean that you are retrieving from the database after the database transaction has been conimitted, you'll want to use the get method, and quite frankly, that tends to be most of the time. For example, if you load a User instance in a Servlet, and you want to pass that instance to a Java Server Page for display purposes, you'd need to use the get method, otherwise, you'd have a LazylnitializationException in your JSP. 3. get() method could suffer performance penalty if only identifier method like getld() is accessed. So consider using load() method if your code doesn't access any method other than identifier or you are OK with lazy initialization of object. Overloaded load0 methods (Hibernate 4.x) Overloaded get() methods (Hibernate 4.x) * cr. getQClasl:clazz; S~l.islizatl:lciclj : c;t,-icct - Sesric1.1 7 . . . .- . <::a c~ct(5tringentit:,:l;lstj~~, C.,e1.ializ3t:le il:l,! : l!-jt,~~ct. >c~j!:..:- ... c..: gct(Clas5 clarz, S~1.13lirabltid: LI=CI.:I'~.:~C!C~EIcckka;ior.le) : Object ,-. ..*:. get(Clar.5 clarz,. Serislisable id,, Lccki?l;tion: Icck0pticn.l : Ot:~!cct . . :..:"c~et(Gring tntit;l;,I21-17~5~1-isliz~1:;lci::II Lcckl;~~lccleIcckhlocle) : Ot.:icct i:.) gtt(Stl.it~g~t~tit:,'l'larr~~.Sel.islizablc iil, Lccl;:Options lc1ck0l:tjct1:> : Object Q) When update() method has to call ? Transient state? Transient state means the object is not associated with session and not presented in database. When there is no record in the database, no question of updating the record: So when the object is in transient state we can't call update() method- Persistent state? Persistence state means the object is associated with session as well as presented in the database. If the object is in the persistent state then the object is said to be synchronized with database. 50 whatever modifications done to the object, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 - An IS0 9001 :2000 Certified Company Page 4http://javabynataraj.blogspot.com 43
  • 44. ..-- -- . ~ . -~ ~.. -- - -...- .. -- > . : Hibernate-Session Methods Mr.Sel<harReddv , ' : / those changes will be updated in the database and vice versa. So we no need to call update() method when object is in 1 I persistent state. I ' , Detached state? II Detached state means the object IS not assocrated with session but presented In the database In this state if we want t o 1, ' do any n~odificationsto the object we should call update() method. Because in thls state the object is not synchron~zed i with database. I I public void saveOrUpdate(0biect object) throws HibernateException;I I I If the record is not there in the database ~twrll try to insert the record. If the record is there in the database it will try t o , ! update the record. 1 Pseudo code o f saveorupdate(): 1. class Sessionlmplimplements Session{ 1 2. public void saveOrUpdate(0bject object){ i 3. 1 4. //SELECT THE RECORD 5. Object obj = session.get(object); j t: //IF RECORD EXIST If(obj != null){ // UPDATE THE RECORD 1 :: updatejobj); , 10. ) else{ // IF RECORD NOT EXIST 11. // INSERTTHE RECORD I 12. save(obj); 13. / 1 Ex: Table ACCOUNT Application code: 1. Session session = SessionUtil.getSession(); 2. session.getTransaction().begin(); 3. 4. Account account = new Account(); 5. account.setAccountld(1001); . 6. account.setName("sekhar"); 7. account.setBalance(6800.00); 8. 9. session.saveOrUpdate(account); 10. 11. session.getTransaction().commit(); 12. 13. //Now saveorupdate() internally calls save(),becauserecord with 9001id is not available in the database. Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666, 23734842 l1 IS0 9001 : 2000 Certified Company - Page 5http://javabynataraj.blogspot.com 44
  • 45. Application code: ~ .- -...-p---p-pp-.-..p..-- . Hibernate-Session Methods. ,. .--. Mr.SeltharRecidy---- ... .. w Table: ACCOUNT 1. Session session = SessionUtil.getSession(); 2. session.getTransaction().begin(); 3. i 4. Account account = new Account(); I 5. account.setAccountld(1001); 6. account.setNarne("selthar Reddy"); I 1 7. account.setBala1ice(8200.00); 8. 9. session.saveOrUpdate(accour~t); ' 10. 11. session.getTransaction().commit(); I 12. ! i 13. //Now saveorupdate() internally class update(). Because the record with 9001id is already exists in the database. i !=NO ,I- Table: i I ACCOUNT I 1001 6800 11 NAME I ACCNO / NAME I BALANCE ) BAL 1 1001 I rekhar Reddy 1 8200 1 I public Connection close0 throws HibernateException; I I Once the transaction is completed we need to close the session. When we close the session all the associated objects I ! with the session will be de-associated from session and associated JDBC connection also closed. It is not strictly necessary to . close the session but you must at least disconnect() it. i 'I public void clear(); I This method is used t o de-associate all the objects from session. 1 Table: ACCOUNT 1002 Kesavareddy 9500 1 Application code: 1. Session session = SessionUtil.getSession(); 1 2. session.getTransa~tion(/begin(); - 3. 4. Account accountl = (Account)session.get(Account.class,1001); 1 5. Account account2 = (A~~ount)session.get(Account.cla~~,1002~; I 6. // Now accountl and account2 objects are in persistent state. 1 7. 8. accountl.setName("new sekhar"); 1 9. account2.~etName("newkesavareddy"); 10. 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I An IS0 9001 :2000 Certified Company -- APage Ghttp://javabynataraj.blogspot.com 45
  • 46. ~ pp ~~ .~ / Hibernate-Session Methods -. .. -. , . Mr.SekharReddy --::I ---- ! -. 1 11. session.clear(); I I 12. //Now account1 and account2 objects are in detached state. !-! 13. / 14. session.getTransaction().conimit(); 1 ~, 1. Session session = Sess~onUtil.getSession(); 2. session.getTransaction().begin(); 3. 4. Account accountl = (Account)session.get(Account.class,1001); 5. Account account2 = ~Account)session.get(Account.class,1002); 6. // Now accountl and account2 objects are in persistent state. 7. 8. session.clear(); 9. //Now accountl and account2 objects are in detached state. 10. 11. accountl.setName("newsekhar"); 12. account2.setName("new kesavareddy"). 13. 14. session.getTransaction().commit(); After execution: ACCOUNT ACCNO BALANCE sekhar kesavareddy 1 I i in the above example, when w e call session.clear() method, accountl and account2 objects will be de-associated ) from the session object. i.e. account1 and account2 objects are moved from persistent state t o detached state. I 9 Now accountl and account2 are in non-transactional state. So even we are committing the transaction the modified I values of account1and account2 are not updated in the database. iI / public void evict(0biect object) throws HibernateException: i This method is used de-associates the specified object from session. Table: ACCOUNT I ACCNO BALANCE 1 I 1001 sekhar 1002 kesavareddy 9500 1I I I I Application code: 1. Session session = SessionUtil.getSession(); r 4. Account account1 = (Account)session.get(Account.class,1001); 1, 5. Account account2 = (Account)session.get(Account.class,1002); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I 1 An IS0 9001 :2000 Certified Company Page 1 - I -http://javabynataraj.blogspot.com 46
  • 47. H ibei-i~ate-SessionMethodsI - - __I. -- -- Mr.SeltharRedcly. 1 u r i 6. // Now accountl and account2 objects are in persistent state. I 7. ' 8. accountl.setName("new sekhar"); 1 9. acco~1nt2.setName{"1iewkesavareddy"); 10. , 11. session.evict(account1); 1 12. // Now accountl in detached state and account2 in persistent state. 13. j 14. session.getTransaction().commit(); i After Execution: ACCOUNT I ACCNO I NAME 1 BALANCE I 1 1001 I sekhar 1 8400 1 I 'i In the above example when w e call session.evict(account1) accountl object will be de-associated from sesslon , I I object. - 9 After calling transaction.commit(), only account2 object will be updated. Because it is in persistent state. i 'i evict() is used to de-associate specified object from the session object. 1002 1 new kesavareddy - ! 1 public boolean contains(0bject obiect); 9500 ~ I It is used t o check whether the object is associated with session or not. I I I I Application code: I I 1. Session session = SessionUtil.getSession(); I 2. 3. Account account = (Account)session.get(Account.class,1001); I 4. System.~ut.println(~'Aftercallingget() method1'); ' 5. 6. if(session.contains(account)){ . , 7. System.out.println("account Is associated with session"); 8. } else{ I 9. System.out.println("accountis not associated with session"); 10. } I 11. 12. session.clear(); 13. System.out.println("After calling clear() method"); 1 14. 15. if(session.contains(account)){ 1 16. Systeni.out.println("account Is associated with session"); 17. } else{ 1 18. System.out.println("account is not associated with session"); - 19. } I i public boolean isConnected(L I To check weather there is a connection is associated with the session or not. 1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company > Page 8http://javabynataraj.blogspot.com 47
  • 48. .- ~ .p..-p---p--.----... . ... - .~.~-~- -.~ Hibernate-Session Methods Mr.Sel<hai-Reddy - . 1. Session session = SessionUtil.getSession(); 2. if(session.isConnected()){ 3. System.out.println("connected"); 4. }else{ 5. System.out.println("not connected"); 6. ? 7. session.close(); 8. if(session.isConnected()){ 9. System.out.println("connected"); lo. }else{ 11. System.out.println("not connected"); 12. } public void flush() thicws HibernateException; This method is used to synchronize session data with database. 1 Application code: I 1. Session session = Sess~onUt~l.getSession(); - 2. session.getTransact~on().begin(); I 3. 4. Account account = (Account)session.get(Account.class,1001); I I 1 5. account.~etName(~'newsekhar"); ( 6. account.setBalance(9500); i I 7. session.flush(); 8. 9. System.out.pr~ntln("Breank..Point and observe the conscle.."); 10. 11. session.getTransaction().commit(); I I 3 In the above example when we call session.flush(), Hibernate checks or compares account object data and ,I corresponding record database. If it finds difference, it will execute update query to update object data into the [ database record. I 9 When transaction.commit() is called it will also check object data and corresponding record data. If it f~nds II different ~twill update object data into database. 9 So after transaction.commit(), we should not call sessioll.flush() because when we call transaction.cornrnit() I session is in sync w ~ t hdatabase I, Batch Processing i9 The execution of series of programs is called batch processing. Batch processing is the process of read~ngdata -- I from a persistent store, doing something with the data, and then storing the processed data in the persistent 1 store 9 Usually we run Batch process, when computer resources are less busy. 9 We are using flush() and clear() methods of the Session API for the batch insert process. I When you need t o upload a large number of records into our database by using hibernate we are using the below code. ! ~ - - - - - - ~ a r e si Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 i 1 An IS0 9001 :2000 Certified Com~anvI ---. - a , --., Page 9http://javabynataraj.blogspot.com 48
  • 49. _ Hibel-nate-Session MethodsI _ Mr.SeltharReddy. - -- 1 Eg: Session session = SessionUtil.getSession(); Transaction tx = session.beginTransaction(); for ( int i=O; i<1000GO; i++ ) { Enlployee employee = new Employee(.....); session.save(employee); 1 The prime step for using the batch processing feature is to set hibernate.jdbc.batch-size as batch size to a number i either at 20 or 50 depending on object size. This shows the hibernate container that every X rows t o be inserted as batch. I Eg: - I. Session session = SessionFactory.openSess~on(); - 2. Transaction tx = sess~on.beginTransaction(); / 3. - 4 for ( int i=O; ic100000; i++) { 1 5. Ernployee employee = new Employee(. ..); I 6. session.save(employee); 1 7. if( i % 50 == 0 ) { // Same as the JDBC batch size I 8. //flush a batch of inserts and release memory: I 9. session.flush(); I 10. session.clear(); 11. } I 12.1 13. ; 14. tx.commit();i 15. session.close(); I Advantage:- Batch processing helps to resolve the problem of OutOfMemoryException. I I public void flush() throws HibernateException; II This method is used t o synchronize the database data with session data. To understand the importance of refresh() I method observe the following scenarios. Casel: with single session, single time calling get() method: I Table: - I I I Application code: ACCOUNT ACCNO BALANCE sekhar 1 1. Session session = SessionUtil.getSession(); 2. session.getTransaction().begin(); i IVaresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified C o m ~ a n vL -- . . Page 10http://javabynataraj.blogspot.com 49
  • 50. . - -. - - - - - Hibernate-session Methods ~ i - . ~ e l t h a r ~ e d c i y- 3. 4. Account account = (Account) session.get(Account.class, 1001); 5. System.out.println("Before updating the database..."), 6. System.out.pr~ntln("Name: " + account.getNanie()); 7. System.out.println("Balance : " + account.getBalance()); 8. , 9. // Break .point. go to database and modify the data 10. ACCOUIVT I 1 1001 sekhar new 1 9500 7 / ACCNO ( NAME I 1 11. System.out.println("After updating the dat~base..."); 12. System.out.println("Name : " + account.getName()); 13. System.out.println("Balance : " + account.getBalance()); 14. 15. session.getTransaction().commit(); 16. 17. session.close(); BALANCE 1 1 Output: Before updaticg the database... Name : sekhar Balance : 8400.0 After ~~pdatingthe database... Name :sekhar Balance : 8400.0 1 Explanation: > When we call the get() on session object, it will h ~ tthe database and get the data from the database and creates - entity object and assign the retrieved data to entity object. And finally that entity object will be cached on the session object. I When we update the data on the database it will not get the updated data. Just it always shows session cached I data. , I I CaseZ: with single session, multiple times calling get() method: Table: ACCOUNT I I ACCNO 1 NAME 1 BALANCE L . , -- Page 11 I Application code: 1. Session session = SessionUtil.getSession(); 2. session.getTransaction().begin(); 3. 4. Account account = (Account) session.get(Account.class, 1001); 5. System.out.println("Before updating the database..."); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 :2000 Certified Com~anv I I 1001 sekhar 8400 http://javabynataraj.blogspot.com 50
  • 51. Hibernate-Session Methods- -- ---- --MI-.SeltharReddy-- l 8. 9. // Break..point...go to database and mod~fythe data 10. ACCOUNT m]NAME I 1 BALANCE 1 /-tsekhar new 1 9500 / 11. account = (Account) session.get(Account.class, 1001); 12. System.out.println("After updating the database ..."); ' 13. Systcm.out.println("Name : " + account.getName()); 14. System.out.println("Balance : " + account getBalance0); I 15. 16. session.getTransaction().cornmit(); I 17. 18. session.close(); - Output: II Before updating the database ... Name : sekhar -1 Balance : 8400.0 After updating the database... I Name : sekhar Balance : 8400.0 / Explanation: > When we call the get() on session object(second time), it will check whether the object is available in session or not. If the object is available in session, it will not hit the database. > In above example with Accno 1001already account object is already available in session object. That's why even we call get() method on session object 2ndtime, it will not hit the database. That's why it didn't display the updated record data of database, instead it displayed previous data only. Case 3: creating multiple sessions. Table: ACCOUNT 1 ACCNO 1 NAME 1 BALANCE 1 ) 1001 I sekhar 1 8400 1I I I I Application code: 1. Session session1 = SessionUtil.getSession(); 2. Session session2 = SessionUtil.getSession(); 3. 4. Account account = (Account) sessionl.get(Account.c~ass,1001); 5. System.out.println("Before updating the database..."); 6. Systern.out.println("Name : " + account.getName()); 7. Systern.out.println("Balance :" + account.getBalance()); Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj.blogspot.com 51
  • 52. ~ - -- . ---- --- --- . .- . ... .. -- - . - ~ . ~- .-. I Hibernate-Session Methods Mr.Sel<hal-Reddv 1 8. I 9. // Break..point... go to database and modify the data ACCOUNT 1 1001 sekhar new 9500 1 I I I 10. account = (Account) session2.get(Account.class, 1001); I 11. System.out.println("After updating the database ..."); I 12. System.out.println("Name :" + account.getName()); ' 13. System.out.println("Balance : " + account.getBalance()); 1 I I I Output:I j Before updating the database... / IVame : sekhar ; Balance : 8400.0 : After updating the database... ' Name : jekhar new I Balance :9500.0 i Explanation: i ! r In the above example, session2 object doesn't have any associated objects. That's why when we call get() I method on session2, it hit the database and executes the select query and retrieve the record and display the Ii updated record of database. i i But here every time we are creating new session object to get the updated Record. To solve the above problem 1 I 1 we can use refresh() method. Case4: using refresh() Table: 1 I ACCOUNT 1 ACCNO ) NAME / BALANCE 1 I I I 1001 / sekhar 1 8400 I Application code: 1 I/ 1. Session session = SessionUtil.getSession(); I ::Account account = (Account) session.get(Account.cIass, 1001); 4. System.out.println("Before updating the database..."); 5. System.out.println("Name :" + account.getName()); 6. System.out.println("Balance :" + account.getBalance()); 8. // Break..point...go t o database and modify the data ACCOUNT 1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I ACCNO I An I S 0 9001 :2000 Certified Com~anv I, I_ . .-- I Page 13 INAME BALANCE http://javabynataraj.blogspot.com 52
  • 53. Hibernate-Session Methods ---- -- ---- - - - .., Mr-SekharReddy ' -2 v-1sekhar new 1 9500 I 9. session.refresh(account); I lo. System.out,println("After updating the database ..."); 11. System.out.println("Name : " + account getName()); 12. System.out.println("Balance : " + account getBalance0); ! Output: I I Before updating the database... I I Name : sekhar Balance : 8400.0 ' After updating the database .. , Name :sekhar new 1 Balance : 9500.0 I ' Explanation: I > In the above example when we call refresh(), Hibernate compares database data and object data. If it finds any 1 - difference it will again execute select query and update the object data. - i public Obiect mergejobiect obiect) throws HibernateException; Consider the following example, Table: ACCOUNT Application Code: ACCNO 1001 1. session.getTransaction().begin(); 2. 3. Account accountl=(Account)session.get(Account.class, 1001); 4. 5. Account account2= new Account(); 6. account2.setAccountld(1001); 7. account2.setName("cherry"); 8. account2.setBalance(6500); 9. 10. session.update(account2); 11. 12. session.getTransaction~).commit(); , Output: org.hibernate.NonUnique0bjectException: a different object with the same identifier value was already NAME sekhar 1 associated with the session: [com.sekharit.hibernate.entity.Account#lOOl] I BALANCE 8400 1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23745666,23734842 I- An IS0 9001 :2000 Certified Company---- -. -- .- Page 14http://javabynataraj.blogspot.com 53
  • 54. - ----..- -- - -~-p--.--p---..---.-.---..p.- ~... - - p-. -- - .- ~~ < Hibernate-Session Methods Mi-.Sel<harRedciy i > In the above example, by calling get() method account1object with identifier '1001' will be there in session. And by calling update()method account2 object with identifier '1001' is also trying to come into session object. It is I I the problem. To avoid this we will go for merge(). :ze:% 15:11 1 1 rl .#:I- ~t1:: .:I . 3:e:z:5.I13i-1 -1-4111114ate1:: 11 I I I I I > In the above example, If we use merge() method instead of update() method, we won't get exception. Just I 1 I I i 9 We can't place two different objects(of same type) with the same identifier in the sesslon object. -- _-------- ------ .-/- I: .311:I: CII-A r~t.I I: -1 111111-1 ;I 'I--. '-._ /- .->' -'-.--,,- ----..-- -_-- ''------ ---- -- ,/-- --.-. ( 13i:~ilL.~rlt2<-lIIIUI 2 :y... <.--- --/--- '------ c- -. -- ---- I I account2 object data will be updated into database. i 1 > merge() method behave differently in different scenarios. merge() method can insert, update, merge the data. - 1 I i To understand more clear about merge() method consider the following cases. ! - I 1 Case 1:merge() method insert the data I j Table: ACCOUNT ! I ! BALANCE I sekhar Application Code: 1. Session session = SessionUtil.getSession(); 2. session.getTransaction().begin(); 4. Account account = new Account(); 5. account.setAccountld(1002); 6. account.setName("cherry"); 7. account.setBalance(4500.00); 8. 9. session.merge(account); 10. 1 After execution: I ACCOUNT 1 ACCNO I NAME 1 BALANCE 1 ( 1001 1 Sekhar 1 8400 1 1002 1 cherry 14500 / 1I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1An IS0 9001 :2000 Certified Company Page 15http://javabynataraj.blogspot.com 54
  • 55. -.----- - - - - - -- - ---- -- - - . - -- - Hibernate-Session Methods Mr.Sel<harRec!dy I 3 In the above example, when we call merge() method, first it will try to load Account object with identifier 1002, As we don't have a record in ACCOUNT table with ACCNO#1002, it will insert Account(1002, cherry, 4500.00j object into database. . Case 2: merge()method update the data I Table: ACCOUNT ACCNO IVAME Sekhar 1002 cherry 4500 Application Code: 1. Session session = SessionUtil.getSession(); 2. session.getTransact~on().begin(); 3. 4. Account account = new Account(), 5. account.setAccountld(1002); 6. account.setName("yeIlareddy"); 7. account.setBalance(5600.00); 8. 9. session.merge(account); 10. 11. session.getTransaction().commit(); 12. 13. session.close(); 1 After executiori: ACCOUNT I ACCIVO NAME I BALANCE ( Sekhar yellareddy 5600 i 1 P In the above example, when we call merge()method, first it will try to load Account object with identifier 1002, As we have a record in ACCOUNT table with ACCNO#1002, it will try to update with latest Account(1002, - 1 yellareddy, 5600.00) object into database. I I Case 3: merge() method merge the detached object data into persistent object Table: ACCOUNT 1 ACCNO 1 NAME 1 BALANCE 1 Sekhar yellareddy Application Code: 1. Session session = SessionUtil.getSession(); 2. session.getTransaction().begin(); 3. 4.. Account accountl=(Account)session.get(Account.class, 1001); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company........... . . . . . . . . . . . . . . . . . . . . . . . ....... ............................ ..... page-%-http://javabynataraj.blogspot.com 55
  • 56. , ..__ .- .. ---.--~-- -.--.~, ' Hibernate-Session MethodsI - Mr.SekharReddy .- .L -, : I I ,-, 11 5. 1 6. Account account2= new Account(); - .. 1 7. account2.setAccountld(1001); i 8. account2.setNarne("kesavareddy"); . ~ 9, account2.setBalance(6500); i I 10. /--. , 11. session.merge(account2]; 12. I . . i 13. session.getTransaction().commit(); j 14. session.close(); 1 After execution: ACCOUNT ACCNO BALANCE yellareddy I I ,In the above example, Before llthline; accountl is in Persistent state, and account2 in detached state.I . - , - . , / > In the above example, when we call merge() method it will check, weather there i i any object associated with the session with same identifier(1001). - > In our example, accountl#1001 object is already associated with session, So merge() method now, Copy the I < - . state of accoun2#1001 object state into accountl#1001 object. After llthline also, account1 is in Persistent , j state, and account2 in detached state. 1 3 When the transaction is committed, As acountl#lOOl(Persistent-state)data is modified, so it will hit the update I ! query, t o update session data with database. Q) What is the difference between merge and update? i i update () :When the session does not contain an persistent instance with the same identifier, and if it is sure use update I for the data persistence in hibernate. i I merge (): Irrespective of the state of a session, if there is a need t o save the modifications at any given time, use I merge(). ! , public Serialiiable getldentifieriobiect object) throws HibernateException; I To know the object identifier value at the runtime, we need to call getldentifierfobject object) I Application code: 1 I Account account = (Account)session.get(Account.class,1001); I Serializable id = session.getldentifier (account); System.out.println("Identifier of Account is :"+ id); '1 1Transaction methods: I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An I S 0 9001 :2000 Certified Company --- I- Page 17-http://javabynataraj.blogspot.com 56
  • 57. ---- - -- - --- -- - - -pp.--p-- - - Hibernate-Sessio~~Methods Mr.Sel<harRedcly I We can apply Transaction management by using transaction object II We can get the Transaction object in 2 ways. Transaction transaction = session.beginTransaction(); I Transaction transaction = session.getTransaction(); beginTransaction0 return different transaction objects. For each and every request transaction object creates a ~ l c l begins new transaction context. I getTransaction0 return same transaction object for every request. We need to call begin() on transaction objecl l o begin the transaction public void persist(0bject object) throws HibernateException; 3 This method is same as save(), but save(object) returns identifier and persist(object) doesn't return any value. I i > When we are using generator classes to generate the identifier, At that time if we want to know identifier value - which is generated by generator class, then we can go for save() method. 1 3 When we don't want to know generated identifier, then i e can foi persist() method. . 1.' M e thod Signatures: public void replicate(0bject object, ReplicationMode replicationMode) throws HibernateException; This method is used to move the object from detached state to persistent state. ReplicationMode has attributes described below. P ReplicationMode.0VERWRITE :this mode reads the processing request and affect the result in database. After committing the transaction the results are stored in database. P ReplicationMode.lGN0RE : this mode ignores the processed request. ~ e a n sit doesn't affect the result in datadase. r ReplicationMode.LATEST-VERSION :this mode reads the processing request and affect the result in database. P ReplicationMode.EXCEPTl0N :this mode reads the processing request and affect the result the database. 1 Application Code: 1. Session session = SessionUtil.getSession(); I ;: session.getTransaction().begin(); I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I An IS0 9001 :2000 Certified Company ---- Page 1ghttp://javabynataraj.blogspot.com 57
  • 58. -- ---..- -. - Hibernate-Session Methods MrSekharReddv --' Account account = (Account) session.get(Account.class, 1001); System.out.println("After get() method"); if (session.contains(account)) { Systeni.out.println("associated"); 1else i System.out.println("not-associated"); 1 session.evict(account); System.out.println("After evict() method"); if (session.contains(account)){ System.out.println("associated"); } else { System.out.println("not-associated"); } session.replicate(account, ReplicationMode.LATEST-VERSIOIV); Systern.out.println("After replicate()method"); if (~ession.contains(account)){ System.out.println("associated"); } else { System.out.println("not-associated"); 1 public void IockiObiect obiect, LockMode IockMode) throws HibernateException; i I If we are updating some group of tables no other person is allowed to update the records on the same table until our I work is completed. So using lock(), if we lock the record it doesn't allow updating from different users till we commit the I transaction. 1 Hibernate defines Several lock modes I P LockMode.NONE :Don't go to the database unless the object isn't in either cache. I I 3 LockMode.READ : Bypass both levels of cache, and perform a version check to verify the object in memory is the same version as that currently exits in the databse. ! 1 P LockMode.UPGRADE: Bypass both levels of cache, and perform a version check and obtain a database-level I I I pessimistic loc upgrade lock, if that is supported. I I I P LockMode.UPGRADE-NOWAIT: same as UPGRADE , but use a SELECT .... FOR UPDATE NOWAIT on Oracle. This disables waiting for concurrent lock releases, thus throwing a locking exception can't be obtained. I I - 9 LockMode.WRITE: Is obtained automatically when Hibernate has written t o a row in the current Transaction. I This is an internal mode and can't bespecified explicitly. 1 I NOTE:this method got deprecated in Hibernate 4.x version I I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i h.An IS0 9001 :2000 Certified Company I - pa e 1 F 'http://javabynataraj.blogspot.com 58
  • 59. . ~ ~ - ~ ~ . A ~ ~ - . ~ - .~ Hibernate-Multi Database Communication By Mr. SeltharReddy 1 Q.) How to work with MYSQL database? ! I install the MYSQL database. I C? Select All Programs 3 MYSQL 3 MYSQL 5.0 3 mysql command line client I Give password i 4. In the MYSQL prompt give the following comr-riands o Create database mydb I o Use mydbI ! ! 6 Now perform database operations normally. I C When you open mysql command line client again just give password, and give use mydb command. (don't give ! create database mydb) i I I' Q.)How t o connect t o multiple Databases using Single Configuration File in Hibernate? I I OracleDataBase Table: 1 I I SQL> desc account; i Name Null? TYpe I -----_----_---_-------------------------- _____-_- ____________ ____ - 1 ACNO IVUMBER(5) i BAL NUMBER(8,2) 1 IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I An IS0 9001 :2000 Certified Company- Pagehttp://javabynataraj.blogspot.com 59
  • 60. , ~~~ .- ~ ~ ~ ~.~ ~ . I Hibel-nate-Multi Database Commu~~ication I --- By Mr. SeltharReddy- ....a..'i - 1 M y S Q L D a t B e Table ; +----.-.+-.-----.--+----.-+-----+-----------+- - - < - --+ I I I Field I Type ( Null I Key ( Default I Extra ( I I 1 acno 1 int(5) 1 YES 1 1 NULL 1 I i I 1 name I char(l5) j YES I I NULL ( 1 Account.iava 1. package coin.neo.hibernate .VO; 2. 3 . public class Account ( 4. prlvate ~ n taccno;* - 5. prlvate Strlng name; 6. privatedoublebalance; 7. 8. publlc int getAccno0 { I 9. return accno; 10. 1 j ll. 12. publlc void seiAccno (lnt accIlo) ( 13. this.accno = accno; 14. 1 15. / 16. public Strrng getName() ( 17. return name; 1 18. I 19. 20. public vold setName (String name) [ 21. this.name = name; 22. I 23. 24. public double getBalance ( ) [ 25. return balance; 26. I 27. 28. public void setBalance(doub1e balance) { 29. thls.balance = balance; 30. I 1 31. I Naresh iTechnologies, Opp. Satyam Theatre, ~ r n e e r ~ e t ,Hyderabad, Ph: 040-23746666,23734842 1 An IS0 9001 :2000 Certified Company I - Page 2http://javabynataraj.blogspot.com 60
  • 61. ~..~.~...................................... . . ~~ --...-- ~ - ~ Hibernate-Multi Database Communication 7By Mr. SekharReddy I 1. package com.neo.hibernate.dao; 2 . 3. import crg.hibernate.Session; 4. lrilport org.hibernate.SessionFactory; 5. import org.hibernate.cfg .C ~ n figuration; 6. 7. import com.neo.hibernate.util.Conn~ctionUti1; 8. import com.neo.hibernate.vo.Account; 9. 10. public class PracticeDao { 11. public static void main(String[] args) { 12. 13. Configuration configuration = new Configuration(); 14. configuration.configure("com/neo/hibernate/config/hibernate.cfg.xml"); 15. SessionFactcry factory = configuration.buildSessionFactory(j; 16. / / Oracle 17. Sesslon oracleSession = 18. factory.openSession(ConnectionUtil.getOracleConnecti~n()); 19. Account oracleAccount = (Account) 20. oracleSession.get(Account.class, 1001); 21. System.out.println("0racle Account table details . . . . ") ; 22. System.out.println("Accno : "+oracleAccount.getAccno()); 23. System.out.println("Name : "+oracleAccount.getName()); 24. System.out.println("Ba1ance : "+oracleAccount.getBalance()) ; 25. //Mysql 26. Session mysqlSession = 27. factory.openSession(ConnectionUtil.getMysqlConnection()) ; 28. Account mysqlAccount= (Account)mysqlSession.get(Account.class, 1001); 29. System.out.println("Mysq1 Account table details . . . . " ); 30. System.out.println("Accno : "-1-mysqlAccount.getAccno()) ; 31. System.out.println ("Name : "+mysqlAccount.getName ( ) ) ; 32. System.out.println("Balance : "+mysqlAccount.getBalance()); 33. 34. 1 35. ) 36. ConnectionUtil.iava 1. package com.neo.hibernate.ut11; 2. 3. import java .sql .Connection; 4. import java.sql.DriverManager; 5. lmport java.sql.SQLException; 6. 7. public class ConnectionUtil { 8. static { 9 . try { 10. Class.forName("oracle.jdbc.driver.OracleDriver~'); 11. Class.forName("com.mysql.jdbc.Driver"); 12. 1 catch (Exception e) { 13. e.printStackTrace0; 14. 1 15. I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 iAn IS0 9001 :2000 Certified Company I 1.- Page 3http://javabynataraj.blogspot.com 61
  • 62. .- ~~ ~ - ~- . ( Hibernate-Multi Database Coi~~munication -- By Mr. SekharReddy--- - --.- ..-?I 1,., . ': 16. 1 ,I public static Con~ectiocget0racleConnection() ( Connection ~ j i 1 i i - j ~ ~ i , 3 : i= 11~11; try ( connection = Driv?rManager.getConnection( "jdbc:oracle:thir:: Plocalhost:1521:XEW, "system", } catch (SQLExcepcion e) ( e.printStaekTrac? ( ) ; 1 return connection; 1 public static Connection ge~MysqlConnection() { Connection connection = null; try { connection = DriverManager.getConnection( "jdbc:mysql://loca1host:33O6/mydb", "root", ) catch (SQLException e) { e .printStackTrace ( ) ; 1 I 37. return connectlon; 1 3 8 . ( 39. ' 4 0 . 1 I "tiger"); 'I I I i Account.hbrn.xm! 1 1. c?xml version="l.0" encoding="UTF-8"3'. ! 1 2. < ! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3 . O / / E l l r ' ! "http://hibernate.sourceforge.neL/!i1berate-mapping-3.O.dtd" > 3. 4 . <hibernate-mapping> 5 . <class name="com.neo.hiberi~ate.vo.Accountr'table=f'ACCOUNT"> 6. <id name="accno" column="ACNO"></id> 7. <property name="name"></property> 8 . <property name="balai?ceMcolumn="BAL"></property> 9. </class> 10. </hibernate-mapping> hibernate.cfg.xml 1. <?xml version='l.Or encoding='UTF-6'?> 2 . <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Conflguratlon DTD 3.@ / / E N u 3. "http://hibernate.sourceforge.net/hibernate-configuration-3.O.dtd"> 1 4. <hibernate-configuration> 5. <session-factory> I 6. <property name="dialect">org.hibernate.dialect.OracleDialect</property> -I 7. <mapping resource="com/neo/h~bernate/mapping/Account.hbm.xmlf'/> 8. </session-factory> I 9. </hibernate-configuration> I I Q.)How to connect to multiple Databases using Multiple Configuration Files in Hibernate? I I IVareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I An IS0 9001 :2000 Certified CompanyI . . . . . . . . . . . . ~ . .. . ... -.- -. .-- 'I Page 4-'http://javabynataraj.blogspot.com 62
  • 63. ~ i b e r n a t e - ~ u l t iDatabase Con~munication Bv Mr. SelcharReddv ~ r a c l e ~ a t a ~ a s eTable: i SQL> desc account; 1 Name Null? TY i1 ......................................... -------- ----------------- ACNO NUMBER(5) NAME VARCHAR2(10) BAL NUMBER(8,2) 1 ( Field I Type I Null I Key ( Default I Extra ( +-------+---------- +------+-----+---------+-------+ I I acno 1 int(5) I YES I I NULL 1 I I ( name ( char(l5) I YES ( ( NULL I 1 I ( bal 1 float 1 YES I I NULL 1 1 ' Account.iava ! Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I An IS0 9001 :2000 Certified Company Page 5-http://javabynataraj.blogspot.com 63
  • 64. . . . . . - .. . ~ -., I Hibernate-Multi Database C o ~ ~ ~ ~ ~ ~ u i ~ i c a t i o n- ....-..- - --- By--Mr. SeltharReddy - -1- , - . . -- I ,,I 1 . package corn.ne2. hibernate. i-c; 2 . 3 . p u b l i c c l a s s Account { 4. p r i v a t e i n t accno; 5 . p r i v a t e S t r i n g n a m ? ; : 6 . p r i v a t e double balance; 7 . 8 . p u b l i c i n t gethccno ( ) i 1 9 . r e t u r n accno;i 1 0 . i 1 1 . / 1 2 . p u b l i c void set,?ccnc ( i n t ?:cn.:?) : 1 3 . t h i s .accno = -::I::: ; 1 4 . ? ; 1 5 . 1 1 6 . p u b l i c S t r i n g getName() { 1 1 7 . r e t u r n name; 1 1 8 . ) 1 9 . : 2 0 . p u b l i c void setName ( S t r i n g nan~ej { j 2 1 . this.name = nasa; i 2 2 . 1 i 2 3 . 1 2 4 . p u b l i c double getBalance0 ( ! 2 5 . r e t u r n belance; i 2 6 . 1 i 2 7 . j 2 8 . p m l i c void setBalance (double iialance) i i 2 9 . t h i s . balance = halance; 1 3 0 . 1 : 3 1 . 1 3 2 . ) PracticeDao.iava 1. package com.neo.hib?rnate.dao; 2 . import 0rg:hibernate. Sessj-on; 3. import com.neo.hibernate.util.SessionUti1; 4. import com.neo.hibernate.vo,Account; 5 . 6 . public class PracticeDao { 7 . public static void main(String [I args) { 8. / / Oracle 9. Session oraclesession = SessionUtil.getOracleSession(); 1 0 . Account oracleAccount = (Account)oracleSession.get(Account.class, 11. 1001); 1 2 . System.out.println("Oracle Account table details . . . . " ) ; 1 3 . System.out.println ("Accno : "toracleAccount.getAccno ( ) ) ; 14. System.out.println("Name : "toracleAccount.getName()); 1 5 . System.out.println("Ba1ance : "toracle~ccount.getBalance()); 1 6 . //Mysql 1 7 . Session mysqlSesslon = SessionUtil.getMysqlSession(); 1 8 . Account mysqlAccount= (Account)mysq1Session.get(Account.c1ass, 1001); 19. System.out.println("Mysq1 Account table details . . . . " ) ; 2 0 . System.out.println("Accno : "tmysqlAccount.getAccno()); 1 1 Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1 I-. An IS0 9001 : 2000 Certified Company--- --i Page 6http://javabynataraj.blogspot.com 64
  • 65. .~.~ - - ~ -. ~ ~.. ~ ~ ~~ .~ ,~ Hibernate-Multi Database Colnmunication By Mr. SeltharReddy , 21. System.out .prlntln("Name : "tmysqlAccount.aetl.!a:ne( ) ) ; , 22. System.out.pr~1ltln("5alance: "tmysqlAccount.qer.Balance()) ; 23. 1 2 4 . 1 I SessionUtil.java - 1. package corr,.neo.hibernate.util; 2. 1 3. import 01-9.hibernate.S-ssion; 4. import org.hibernate.SessionFactory; 1 5. import org.hibernate.cfg .Configuration;i 6. import org .ja:<en.Eunction .ConcatFunction; 1 7. 8. public class SessionUtil { 9. 1 10. private static SessionFactory oraclFactory; 11. private static SessionFactory mysqlFactory; 1 12.I stacic ( 13. n r ? c l Factory = new Configuration i : . ranfigure ( . I ;;: "com/neo/hibernate/config/~racle.hibernate.cfg.xml") -- .buildSessionFactory(); ' 1 16. mysqlFactory = new configuration().configure( , I 17. "corn/neo/hibernate/config/~nys~ql.hibernate.cfg.xml") - 18. .buildSessionFactory(!; 1 19. 1 20. I ;;: public static Session getOracleSession() [ return oraclFactory.openSession(); 23. 1 1 24. 25. public static Session getMysqlSession() { 1 26. return mysqlFactory.openSession(); 27. 1 28. public static void main(String[] args) { 1 29. System.out.println(getMysqlSession()) ; 30. 1 ' 3 1 , ! 1 Account.hbm.xrnl 1. <?xml version="l.0" encoding="UTF-8Ir?> 1 2. <!DOCTYPE hibernate-rnapplng PUBLIC "-//Hibernate/HlbernateMapping DTD 3.O//ENU I "http://h~bernate.sourceforge.net/hibernate-mappng-3.0td"> 3. 4. <hibernate-mapping> 5. <class name="corn.neo.hibernate.vo.Account" table="ACCOUNT"> I 6 - <id name="accno" column="ACNO"></id> - 7. <property narne="name"></property> 8. <property name="balance" column="BAL1'></property> 1 9. </class> I 10. </hibernate-mapping> I I I Naresh I l.echnolog~es,Opp. Satyam Theatre, Ameerpet, ~ ~ d e r a b a d ,Ph: 040-23746666, 23734842 I An I S 0 9001 :2000 Certified Company I I __I Page 7http://javabynataraj.blogspot.com 65
  • 66. Hibernate-Multi Database Comn~unication Bv Mr. SeltharReddv :- 2. <!DOCTYPE hibernate-configuration P U B L I C M - / / H i b e r n a t o , i S i b e r n a ~ : e C3:lfiguration DTD 1 3 . O//EN1' 3 . lqhttp://hiberliate.soilrc?forge . n e t / h i b e r n a t e - c o n f i g u r a ; i : ~ ; - .C . 5L?":, 1 4 . - , i 5. <hiberna~-3--;l:~i?i-iil;icat i~:i'. / 6. <session-fact~ory; . . I 7 . <proL2;+rL:,: ;:,;fie- ' ' j ~ ~ , ~ ~ ~">erg.l-liberllate.di315~;;.; . i . . i ~ > i i [ ~ ~ - ~ ~ ~ < / p r c p e r t ) / > ' 8. <property !?are="zci~~~eccisn.url ">jdbc:mysql://loca?i~ss:::-- .....- - . . - > j C ; G . ' r i ~ - . . - ~ ' -.-.-.,>,</property>~ -- 9. <property name= "coi~nection.usernan~e">root</prope~-t;~:;, I 10. <prcpert;: n ~ r ~ , ~ - - " ~ ~ ~ : ~ ! ~ i 3 z t 1 i ? ~ . p ~ ~ ~ ~ ~ ~ - d " > t i g e r < / ~ r ~ p e r - ~ : ~ , : ~ ~ / 11. <property !??me="connection.c'river~class">com.n~ysql.i d b e . D~:I.:;ar</property> 12. <rnappi!?g rescurile= "co!ii/neoihiberna te/nlappii~g...~.?z~i~ci?:r. ?!hi!..<rill" /> 1 13. </session-factor!:; 14. </hibernate-c3r.fiauratio~n> oracle.hibernate.cfa.xml 1. <?xml version= '1.0'encoding= 'UTF-8'?> 2. <!DOCTYPE hibernate-configuration PUBLICu-//Hibernate/Hiberna~eConfiguration DTD 3.O//EMV 3. "http://hibernate.scurceforqe.net/hibernate-co11figuration-3.O.dtd"> 4. < h i b e r n a t e - c c n f i g u r a t i o n > 5 . <session-factory> 6. <property n-1ln~="dia1ect">crg.h~ibernate.dialect.Orac?e9Cialect</property> i 7 . <property name="cor1nection.url">jdbc:oracle.:thin:@localhcst:1521:XE</property>-- 8. . " ~ ' . . ' , " - L . , .- -,.^- ! I - - . > . - , , . . I . ; - .,<.,,-. i3!ne11>S,Stem.',/F : v . , . . - . . . . > - i - : . ' - . . . ., . . . . . . . . .:-. . L ' . ' - L . '..., P - . L .. . ' <property name= "con~~ection.password">tiger</property> 10. . <property name=rfconnection.driver~classf'>oracle.jdbc.driver.OracleDriver</property> 12. <mapping resource="corn/neo/hiberna te/rnappinq/Accouli t.hbrii.xml " /> 14. </hibernate-configuration> I Naresh iTechnologies, Opp. satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 :2000 Certified Company I - page-g--.-http://javabynataraj.blogspot.com 66
  • 67. Hibernate-Generators using XML -- -- --- --- - . . Mr.SekharReddy I -- - .--. -riWI Generator classes > Generator classes are used to generate the 'identifier' for a persistent object. i.e. While saving an object into the I database, the generator Informs to the hibernate that, how the prlrllaly key value for the new record is golng t o generate 3 Hibernate using different primary key generator algorithms, for each algorithm internally ajava class is there for its 1 implementatiorl i' . 3 All Generator classes has to implement 'org.hibernate.id,ldentifierGeneratorU interface, And has to override i generate() metliod. The logic to generate 'identifier' has to write in this method I > In built-ingere~atorclasses, identifier generation logic has implemerited by using JDBC. 1 > If we want we can write the user defined generator class and it should implement 'org.hibernate.id.ldentifierGenerator' interface and has to override generate() method. - > To configure generator class we can use <generator /> tag, which is ttie sub element of <id/> tag - > <generator/> tag has one attribute called "class" with which we can specify generator class-name. I i 9 While configuring <generator /> tag in mapping file, if we need to pass anv parameters to generator class then we ! can use <param /> tag, which i s the sub element of <generator/> tag, 1 Example: HEM <hibernate-niapp~ng> 1 I <class .. > I ~<Id ....> I 1 <generator class="generator-class-namet'> I <param name="param-nameH>param-value</param> I I </generator> I </rd> i 1 </class> I </hibernate-mapping> I I I I 1 The following are the list of main generators we are using in the hibernate framework I i 1 1. sequence 1 2. assigned I 3. increment I 5. seqhilo I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -- An IS0 9001 :2000 Certified Company- -- - Pa F I -http://javabynataraj.blogspot.com 67
  • 68. 1 6, identify 7. native 8. uuid 1 9 guid 10.select 11. foregin I 1 In the above generators list, are used for int,long,short types of primary keys, and uuid, guid are used when the pri~nary key column type is String type (varchar2) 1.) sequence (or~.hibernate.id.SequenceGenerator) I ' > This generator class is database dependent it means, we cannot use this generator class for all the database, we should know whether the database supports sequence or not before we are working with it - - . P Not has the support with MySq! I - ~ P Here we write a sequence and it should be configured in HBM file and while persisting the object in the database ,, sequence is going to generate the identifier and it will assign to the Id property of persistent object, Then it will store ' : the persistent object into Database. NOTE: MYSQL even won't allow to create SEQUENCE Object in that database. Then where is the question of calling that from hibernate applicat~on? 1 NOTE: When we configured generator class for an entity, then we no need to assign identifier value t o entity object / whiie saving the entity. Even we assign the identifier value to entity, it will not consider our assigned value, it will use I ! / generator class generated value as identifier value. It applies to all generator classes. I 1 Steps to work with "sequence" Renerator I Step 1:Create a sequence 1 SQL> CREATE SEQUENCE ACCNO-SEQ START WITH 1000 INCREMENT BY 1 To get next value SQL> SELECT ACCNO-SEQ.NEXTVAL FROM DUAL; To get current value I SQL> SELECT ACCNO-SEQ-CURRVAL FROM DUAL; Step 2: configure the sequence in hbm file. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I An I S 0 9001 :2000 Certified Company -. I - Page 2http://javabynataraj.blogspot.com 68
  • 69. ....... . . . . . . . .-- -- --- ...................... ....... ........ ... -- - Hibernate-Generators using XM L! -. . . . .-- ---. . . Mr.SekharReddp., - , rims i II 1 <id name=" accountld " column="ACNO"> <generator class="org.hibernate.id.SequenceGenerator" > ! <param name="sequence">ACCNO-SEQ </param> </generator> 1 </id> I (OR) <id name=" accountld " column="ACCNO">- 1 <generator class="sequenceU/> </ld> I 1 NOTE: If we don't configure any sequence name then it will take default sequence name(HIl3ERNATE-SEQUENCE ). But 1 I hibernate won't create the sequence, if already sequence is available with name "HIBERNATE-SEQUENCE", then it is! !I ' used by hibernate. Otherwise hibernate raises the exception. I 1 NOTE: But remember, if we enable hbrn2ddl.auto property in hibernate configuration file, then hibernate will create the 1. .- database objects if they are not exist. I NOTE: It is not advisable to use the default sequence, always prfer to create a different sequence to each enitity 1I seperately. I I 1 Step 3: Create the entity and save it without assigning identifier. i1 1. Session session = SessionUtil.getSession(); I 2 . session.getTransaction ( ) .begin( ) ; 3. 1 4. Account account = new Account ( ) ; 5. account.setName ("sekhar"); 1 6. account.setBalance (5000); - 7 . 8. Serializable id = session.save (account); I 9 . 10. System.out.println (flAccountis created with accno : "+id); ( 11. session.getTransaction ( ) .commit ( ) ; I Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, ~ ~ d e r a b a d ,Ph: 040-23746666, 23734842 I I An IS0 9001 : 2000 Certified CompanyI Page 3- 1http://javabynataraj.blogspot.com 69
  • 70. -- - -- -- - -- - -- ; Hibei-nate-Generators using XML Mr.SekharRecici,__ IVOTE: When we execute the above code, we can find the sequence execution query on the console, which is used to get identifier for the saving enitity. 1 Internal Code 1 public class SequenceGenerator implements PersistentldentifierGenerator, Configurable { I public static final String SEQUENCE = "sequence"; I .1 public void configure(. .){ I sequenceName = PropertiesHelper.getString(SEQUENCE, params, "hibernate-sequence"); // default sequence name parameters = params.getProperty(PARAMETERS); 1 public Serializable generate(. . . ) { Preparedstatement st =. . ..prepareSelectStatement(sql); Resultset rs = st.executeQuery(); rs.next(); Serializable result = . . iterate results... return result; 1 1 I NOTE: ow onwards for the following generator classes Ijust give the HBM configuration, you can u;e the same entity saving logic(which we used in the above example as part of step-3) to test them. / 9 This generator supports in all the databases I I 9 This is the default generator class used by the hibernate, if we do not specify <generator/> element under <id/> 1 element, then hibernate by default assumes it as "assigned" generator class. 9 If generator class is assigned, then the programmer is responsible for assigning the identifier value to entity before saving into the database I 1 . HBM: <id name=" accountld " column="ACCNO"> <generator class="org.hibernate.id.Assigned"/> </id > (OR) ! I Naresh i Technologies, Opp. Satyam 'Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1 An I S 0 9001 :2000 Certified Company , - Page 4--'http://javabynataraj.blogspot.com 70
  • 71. --- ---- - . . ~ ~ . - ~ ~ ~ . ... - - - .~ --I ' Hibernate-Generators using XM-- L -- Mr.SekharReddy. .- -- .- 1, . . . -%a I- <id name=" accountld " column="ACCNO" /> Internal Code: I public class Assigned implements Identif~erGenerator,Conf~gurable{ public Serializable generate(... ){ final Serializable id = . . . get the developer glven id. if (id==null){ throw new Identif~erGenerat~onException( "ids for this class must be manually assigned before calling save():" t entityName); 1I return id; 1 i } I NOTE. Whrle testing don't asslgne ident~fiervalue to entity and then try to save entity then ~tthrowsI - IdentifierGenerationException. ! NOTE: While testing with assigned generator class, identifier type in enity should be some object type rather than iII primitive type. ! I ' > This generator supports in all the databases, so it is database independent generator class. I I This generator is used for generating the id value for the new record by using the formula Max of id value in Database + 1 i > If there is no record initially in the database, then for the first time this will saves primary key value as 1. 1 I i . HBM: <id name="accountld" column="ACCNO"> II <generator class="increment" /> </id> I (OR) 1 <id name=" accountld " column="ACCNO"> I <generator class=" org.hibernate.id.lncrementGenerator " /> I </id> 1 Internal Code: ;:;+ -*!v-.5 *>:.,;. .;, ,x :, ~ :.,,<,;: ..,.. .-...--.-<!..:;.....-r@ I public class ~;@$@;@<~~tJj:$?~g.~$~~~$implements IdentifierGenerator, Configurable { - ~ public synchronized Serializable generate(. . .){ I i f (sql!=null) { getNext( session ); I 1 return ...final number after adding '1' ,-I Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 ...-. ---. --.......- ...... .... . ..-...--- An I S 0 9001 :2000 Certified Company-~~ .----. - Pages-http://javabynataraj.blogspot.com 71
  • 72. ~ ~.~ - ~ ~. . - -. . -..---.- ,-3 1 Hibernate-Generators using XML Mr.Sel<harReddy_-., public void configure(. . .) { sql = "select max(" + column + ") from " + buf.toString(); I private void getNext( Sessionlmplementor session ) { ! Preparedstatement st = ....prepareSelectStatement(sql); Resultset rs = st.executeQuery(); if ( rs.next() ) { next = rs.getLong(1) + 1; 1 1 The HiLo Algorithm - I The HiLo (High/Low) algor~thmknows how to generate unique number series using t w o values: the high and the low. I -Ihe high value is used as a base for a series (or range) of numbers, while the size of this series is donated by the low 1 value. A unique series is generated using the following steps: I I ' 1) Load the and atomically increment the high value 1 2) Multiple the high value by the low value (max*low), the result is the first number (lower bound) of the current series 3) The last number (higher bound) of the current series is donated by the following calculation: (max*low)+low-1 I 4) When a client needs to obtain a number the next one from the current is used, once the entire series has been / exhausted the algorithm goes back to step 1 6' 1 I I I Example: suppose that the current high value in the database is 52 and the low value is configured to be 32,767. When I the algorithm starts is loads the high value from the database and increments it in the same transaction (the new high I value in the database is now 53). The range of the current numbers series can now be calculated: 1 I Lower bound = 52*32767 = 1,703,884 I Upper bounds = 1,703,884+32,767-1= 1,736,650 1 All of the numbers in the range of 1,703,884 to 1,736,650 can be safely allocated t o clients, once this keys pool has been 1exhausted the algorithm needs to accessthe database again to allocate a new keys pool. This time the hiih value is 53 (immediately incremented t o 54) and the keys range is: I Lower bound = 53*32,767 = 1,736,651 Upper bounds = 1,736,651+32,767-1 = 1,769,417 And so on IThe big advantage of this algorithm is keys preallocation which can dramatically improve performame. Based on the low I I I IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1 I-An IS0 9001- : 2000 Certified Company _I- Page 6http://javabynataraj.blogspot.com 72
  • 73. -- -- -- - - ---- - - -- .- --- -- ---- -- -- -- -- -- ---- Hibernate-Generators using XM L M1-.Seltl?arReddy , value we can control the database hit ratio. As illustrated using the 32,767 we hit the database only once in a 32,767 , ' generated keys. The downside (at least by some people - but in my opinion this is a none-issue)is that each time the algorithm restarts it leaves a 'hole' in the keys sequence. Hibernate has several HiLo based generators: TableHiLoGenerator, MuItipleHiLoPerTableGecierator, , SequenceHiLoGenerator TableHiLoGenerator A simple HiLo generator, uses a table to store the HiLo high value. The generator accepts the following parameters I o table -the table name, defaults to 'hibernate-unique-key' I o column -the name of the column to store the next high value, defaults to 'next-hi' o max-low - the low number (the range) defaults to 32,767 (Short.MAX-VALUE)I i A table HiLogenerator which can store multiple key sets (multiple high values each for a different entity). This is useful ! when we need each entity (or some of the entities) has its own keys range. It supportsthe following parameters: I o table - the table name, default t o 'hibernate-sequences' 1 o primary-key-column - key column name, defaults to 'sequence-name' o value-column - the name of the column to store the next high value, defaults to 'sequence-next-hi-value' , o primary-key-value - key value for the current entity (or current keys set), default to the entity's primary table name / o primary-key-length - length of the key column in DB represented as a varchar, defaults to 255 o max-low - the low numer (the range) defaults to 32,767 (Short.MAX-VALUE) II The generator uses a single table to store multiple high values (multiple series), when having multiple entities using the I same generator Hibernate matches an entity to a high value using the primary-key-value which is usually the entity name. A sample table can look like I Naresh iTechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 : 2000 Certified CompanyI Page 7http://javabynataraj.blogspot.com 73
  • 74. .~ .~ ............ .-.-pp--p----.---pp- ........... ..... r Hibernate-Generators using XM L MI-.Sel<harRecldv'1 A simple HiLo generator but instead of a table uses a sequence as the high value provider. o sequence - the sequence name, defaults to 'hibernate-sequence' o max-low - the low number (the range) defaults to 9. , r This generator is database independent , r hilo uses a hi/lo alogorithm t o generate ~dent~f~ers. 1 r Hilo algorithm generate identifiers based on the given table and column(stores high value). Default table is 'hibernate-unique-key' column is 'next-hi'. I HBM: I -I < ~ dname="accountld" column="ACCNO"> <generator class="hilo" > <param name="table">HIGH-VAL-TAB</param> , <param ndme="column">HIGH-VAL-COL</param> I Internal code ! class TableHiLoGenerator extends TableGenerator { I I 1 class TableGenerator { I i i public static final String COLUMN = "column"; public static final String DEFAULT-COLUMN-NAME = "next-hi"; II i public static final String TABLE = "table"; public static final String DEFAULT-TABLE-NAME = "hibernate-unique-key"; 1 3 It is just like hilo generator class, But hilo generator stores its high value in table, where as seqhilo generator I stors its high value in sequence. I IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I L. An IS0 9001 :2000 Certified Company I Page 8http://javabynataraj.blogspot.com 74
  • 75. .-- --.--... . ~~ ~ -~~ .~ ~~ -.-~ ~~ ~ . . . . . . . , Hibernate-Gelieratol-s using XML Mr.SeltliarReddg7 1 HBM:I - <id name="accountld" column="ACNO"> <generator class="seqhilo" > I <param name="sequence">~~~~~-SEQ</param> <param name="max-lo">S</param> </generator> </ld> (OR) 1 <id name=" accountld " coiumn="ACCNO"~ <generator class="seqhiloU> <param name="org.hibernate.id.SequenceHiLoGenerator ">ACCNO-SEQ</param> i <param name="max-lo">5</param> </generator> 1 </id> Q.) How t o work with MYSQL database? a install the MYSQL database. c3 Select All Programs 3 MYSQL 3 MYSQL 5.0 3 mysql command line client a Give password In the IMYSQL iiomp't give the following commands o create database mydb o use mydb Now perform database operations normally. c3 When we login to database next time onwards don't give create database command, just give use command. 9 This is database dependent, actually it's not working in oracle. 9 Identity columns are support by DB2, MYSQL, SQL SERVER, SYBASE and HYPERSYNCSQLdatabases. 9 This identity generator doesn't needs any parameters to pass Syntax t o create identity columns in MYSQL database: CREATE TABLE STUDENT( SNO INT(10) NOT NULLAUTO-INCREMENT, COURSE CHAR(2O), FEE FLOAT, NAME CHAR(20), PRIMARY KEY (SNO) 1 HBM: 1 <id name=" accountld " column="ACNO">-- <generator class="identity" /> 1 </id> / Example: To create identity columns in MYSQL database. I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I ! An I S 0 9001 :2000 Certified Company :I page9 --http://javabynataraj.blogspot.com 75
  • 76. - .-..- - -- - -- --- - ----- ---- -- Hibernate-Generators using XML---- ~ i - . ~ e k h a r ~ e d d'- . I 7.)native I 3 native is not having any generator class because, it uses internally identity or sequence or hilo generator classes. I P native picks up identity or sequence or hilo generator class depending upon the capabiliti2s of the underlying * I database. I - HBM: <id name="accountld" column="ACIVO"> IIVareshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I An I S 0 9001 :2000 Certified Company -1 Page 10http://javabynataraj.blogspot.com 76
  • 77. Hibernate-Generators using;XML NOTE: test with niysql and oracle 1 C3 If we connect to mysql it takes identity. C3 If we connect to oracle it takes sequence. I I d uuid uses a 128-b~tuuid algorithm to generate identifiers of type string. I d uuid generated identifier is unique with in a network. I c3 uuid algorithm generates identifier using IP address. .,. C3 uuid algor~thmencodes identifier as a string(hexadecima1digits) of length 32. 1 C3 Generally uuld is used to generate passwords. 1 HBM: - <id name="accountld" column="ACNO"> ~ <generator class="uuid" > - </generator> </id> <id name=" accountld " column="ACCNO"> <generator class="org.hibernate.id.UUIDHexGenerator " > </generator> 1 </id> ' select: select retrieves a primary key assigned by a database trigger by selecting the row by some unique key and I 1 retrieving the primary key value. I I 1 I guid: uses a database generated guid string on MS-SQL and MYSQL. I foreign: foreign uses the identifier of another associated object. Usually uses in conjunction with a <one-to-one> I primary key association. I - User Defined Generator class - When we feel the existing generator classes are not fit for our requirement, then we will go for user defined I I generator class. 1 Steps t o implement user defined generator class. i i 1 Step 1:Take any java class and implement org.hibernate.id .IdentifierGenerator and override generate() method. In this 1 I method implement the identifier generation logic as per the requirement. I I I - I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I I An IS0 9001 :2000 Certified Company -.- Page 11http://javabynataraj.blogspot.com 77