You are on page 1of 328

Edited by Foxit PDF Editor

Copyright (c) by Foxit Software Company, 2004 - 2007
For Evaluation Only.

Hibernate

.-.

-.

pp.pp.--p.-

~

... -. . .

.

~

1, Hibernate-Introduction

-

.

M r.Sek11arReddy
-

-

..

-

.

-.
x.

Q) Where actually java i s used?
Q

Java is used t o develop the enterprise applications

Q

Enterprise means business organization

*

Business organization provides servic2s

!

1
1

Q) What i s Enterprise Application?

*

,.

Computerizing business services

Architecture o f Enterprise Application

-

. -

Controller Layer

I

I

Client Layer

Presentation

-.

I

I--..-

+ . a < * . :

" -

J

Layer
:

-

_

I
I
1

I

"

I
1
I

i

1

Client Layer:

3 It is browser software.
Controller Layer:

1

P Receiving user request from client (calling request)

1

P Validating the user input

Ii

>
>

I

>

Capturing the user provided data

Calls the business method t o get business services and get processed data
Keep the processed data in memory(request/session/application scope)
Finally forwarding the request t o VIEW.

IVote: should not write business-Logic/Data-Access-Logic in the Controller Layer. Because that is not reusable

I/

'~

Presentation Layer:

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 t o browser
Business/Service Layer:
1I

Naresh i Technologies, Opp. Satyam Theatre, Anleerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 . 2000 Certified Company
L
-- -.-- --- ---..--. - - -- - .-- - .- -- --- -.
http://javabynataraj.blogspot.com
2
Page 1

-

-.-

. ,

-

.

..-

--

-

-- .

L
.-

i

O Receiving request from Controller Layer
1

P Contacting the Data Access Layer t o get the database data
3 Implementing the business logic
3 Return the control/processed-data t o Controller Layer
PersistentIData-Access Laver:

i

Receiving the request from business Layer

P Contacting database to get the database data

I

O Return the accessed data t o business Layer

I
Data Laver:

>

1

'

-

It is a database.

Q) What are t h e different logics available in Enterprise Application?

I

Presentation Logic: Logic used t o present the output/input.
Application/Controlling Logic: Logic used t o control the flow of application.
Business Logic: Programmatical implementation of business rules is nothing but business logic.
Data Access Logic: Logic used t o contact the Database.

I

I

-

1
I

-

I

I
/

j

I

Q) What are t h e Sun Microsystems technologies and frameworks in enterprise application development?

'I

I

/

.'

I

Presentation Layer
JSP

Controller Layer
Servlets
JSF

'
I

Data Access Layer
JDBC
Ejb2 entity beans
Ejb3 entitys[JPA ] (java

Business Layer
EJB2 session beans
EJB3 session beans
WIDB(Message Driven
Beans)
WEB-SERVICES

t

persistence API)

Q) W h a t are t h e non-Sun Microsystems technologies and frameworks i n enterprise application

1 development?
1 1 Controller Layer

Presentation Layer
HTML
Velocity
Freemarker
Flex

struts
Spring Web MVC
-- Wicket
Tapestry
Flash

'I
I

'

I

~ u s i n e kLa-yer
Spring AOP
Spring JEE
WEB-SERVICES

Data Access Layer
Hibernate
lbatis
Toplink
JDO
Spring DAO
Spring ORM

I

1

,

1

1 Objective of Hibernate: Developing Data access layer of an Enterprise application

I
L--.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An..IS0
9001 : 2000 Certified-Company
-.
.
- -- .- -- --. .
--

I
I

1

http://javabynataraj.blogspot.com
Page 23-

, Hibernate-In troduction
'

!
I

Q) What is persistence i n a java based enterprise application?

>

The process of storing enterprise data in t o relational database is Iknown as persistence

Q) What is the traditional style o f achieving persistence in java based enterprise application?
I

>

Sending SQL statements t o the Database using JDBC API

I
I

'

I

I

Q.) What are the iimitations o f the traditional approach?

'i Application portability t o the Database is lost (Vendor lock: diff SQL statement for the db's)

I

1

3
I

Mismatches between Object oriented data representation and relat~onaldata representation are not
properly addressed

I

I

3 Requires the extensive knowledge of DB

I

I

P Manual operations on Resultset

7

I

I

v

I

For every problem while commun~catingwith the database (us~ng
JDBC), it throws same

-

exception(java.sql.SQLException). As SQLException is checked exception, so we must write code in try-

I
I
I

,

catch block or throws has t o be specified.

>

I

I

Need t o implement caching manually

3 In the Enterprise applications, the data flow with in an application from class to class will be in the
form of objects, but while storing data finally in a database using JDBC then that object will be

/

I

iI
I

1
I

I

converted into text. Because JDBC doesn't transfer objects directly.

1!

;

'I

4.) w h a t is an alternative for traditional approach?

>
>
>

ORM (Object Relational mapping)
It is technique of mapping objected oriented data t o that of relational data
Through ORM technique persistence services (database) are provided t o business layer in pure object
oriented manner by overcoming all limitations of the traditional approach

I

I

Q.) W h a t is Hibernate?

& Hibernate is an ORM implementation

>
i

!I

Hibernate is an Open source

b Hibernate is a framework

>

Hibernate invented by Gavin King. He also invented JBoss server and JPA

-

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An I S-0 9001 : 2000 Certified Company
--

http://javabynataraj.blogspot.com 4 I
Page 3

~

~

~

~

~~

~.

Hibernate-In troduction

.

~-~

--.
._-_.. - -"..._._..

~

~

~~

.~~

~

.

Mr.SekharReddy
..-.

----

?
,-.>
,>"<

_
.U
l

3 Hibernate is a non-invasive framework, means it won't forces the programmers t o extend/implement
arly class/interface, and in hibernate we have all POJO classes so its light weight

k Hibernate can run w i t h 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 t o 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

I

become portable across the multiple databases

I

I

i

I

9 Hibernate generates efficient queries for java application t o communicate with Database
9 It provides fine-grained exception handling mechanism. In hibernate w e only have Un-checked

I

exceptions, so no need t o write try, catch, or no need t o write throws (In hibernate we have
the translator which converts checked t o Un-checked)

.-

1
I

i

,

3 it supports synchronization between in-memory java objects and relational records

>

I
!

Hibernate provides implicit connection pooling mechanism

j

Hibernate supports Inheritance, Associations, Collections

I
1

1

1
I

3 Hibernate supports a special query language(HQL) which is Database vendor independent
database

>
>
>

I

(

I
1-

i

1I

Hibernate addresses the mismatches between java and database
Hibernate provides automatic change detection

I

9 Hibernate often reduces the amount o f code needed t o be written, so it lrnproves the productivity

I

I
I
-1

/

9 Hibernate has capability t o generate primary keys automatically while we are storing the records into

>

I

i

Database objects (tables, views, procedures, cursors, functions ...etc) name changes will not affect
hibernate code

I

i

Supports over 30 dialects
Hibernate provides caching mechanism for efficient data retrieval

>
>
>

Lazy loading concept is also included in hibernate so you can easily load objects on start up time
Getting pagination in hibernate is quite simple.

i

Hibernate Supports automatic versioning o f rows

I

I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0
9001 : 2000 Certified Company
-. .. - -.
-

i
.

http://javabynataraj.blogspot.com
Page 45

I

I

Hibernate-Introduction
-

---

I
i

iI

-

McSekharReddy
-

--

-.-

1

3 Hibernate provides transactional capabilities that can work with both stand-alone or java Transaction
API (JTA) imple~nentations...etc

1

.

.
,

I

i

I

I

,

1

Q.)What are the disadvantages of hibernate?

II

3 Since hibernate generates lots o f 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

I

I

Hibernate supports annotations, apart from X M L

understanding of conlposite mapping is complex

/

P Hibernate does not support some type of queries which are supported by JDBC

1
I

9 Boilerplate code issue, actually we need t o write same code in several files i n the same application,

,'
I

but spring eliminated this

I

1

1

Hibernate Architecture

n
A

1

java application

\L'

Hibernate API

I-+r---

H i l r e i n a l e E ngi n e

.
-

configuration file

\

I, D E C

'./

1

Data base

Java Application makes use of hibernate API methods calls t o inform the persistent needs t o
hibernate. Then Hibernate engine generate .lDBC code that corresponds t o the underlying DB by using
mapping file and configuration file information.

II

r.

We can also find the architecture diagrams as follows

I-,

1lI

I

...
I

i

iL_.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0
9001 : 2000 Certified Company
_ - __-.-- .- -

http://javabynataraj.blogspot.com
Page 56

1
(

I

1

..>** & .. . . .blogspot. . . .. ... f . ~ . Hyderabad..r." -. . .. .. . . . . JTA ..-. .".-. . .-... . . Satyam Theatre. .-.23734842 An IS0 9001 : 2000 Certified Com~anv http://javabynataraj. .. . . . Ph: 040-23746666.com Page 67 I i I . . . .'*. . .&.*. . I -- I I Naresh i Technologies... . . Opp...... ."*"? . . . Ameerpet. JNDl *... .

/
1
1

1

'
I

,

2.

3.

< c l a s s n a m e = " E n t l t y 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 ' >
< l d name="ld v a r l a b l e name" c o l u m n = " p r l m a r y column name l n d a t a b a s e " />
< p r o p e r t y n a m e = " v a r i a b l e l name1' column="column name l n d a t a b a s e " />
< p r o p e r t y n a m e = I 1 v a r l a b l e 2 name" column="column name l n d a t a b a s e " />
</class>

4.
5.

6.
7 .

8.
9 . </hibernate-rnapplng>
Syntax O f Mapping Annotations:
1. @ E n t i t y
2 . @ T a b l e ( n a m e= " t a b l e name i n d a t a b a s e " )
3 . p u b l i c c l a s s EntityName {
4.
@ Id
5.
@Column(name= " p r i m a r y 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;
10.
@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;
12.
/ / setters & g e t t e r s

1

13.

Q.) What i s hibernate configuration file?
i

It is an X M L 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
specified t o the hibernate

I

>

1

Z Standard for this file is <hibernate.cfg.xml>

I

Hibernate uses this file t o establish connection t o the particular database server

,
t

i

3 We must create one configuration file for each database we are going t o use, suppose if we want t o

1
ij

connect w ~ t h2 databases, like Oracle, MySql, then we must create 2 configuration files.
No. of databases we are using = That many number of configuration files

I
(

>

>

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

1

configuration by using .properties file,

I

always recommended t o use.

j., \

but from 3.x XML came into picture. XNlL files are

I

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. <session-factory>

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
~-

http://javabynataraj.blogspot.com 8

~Tge8-

I

'

Q.) What i s hibernate mapping file?

3 In this f ~ l ehibernate application developer specify the mapping from entity class name to table name
and entity properties names t o table column names. i.e. mapping object oriented data t o relational
data is done in this f ~ l e

1

i

Z Standard name for this file is <domain-object-name.hbm.xml>

I
I

r

Z Mapping can be done using annotations also. If we use annotations for mapping then we no need t o
write mapping file.

t w o ways

XML
Annotations

Syntax Of Mapping xml:
1. <hibernate-napping>

i

I

I
I

Z From hibernate 3.x version on wards it provides support for annotation, So mapping can be done in

1

I

I
I

In general, for each domain object we create one mapping file
Number of Entity classes = that many number of mapping xmls

o
o

i

Naresh i 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'~>Driver
Class 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 -->
12
<property name="show-sqll'>true/false</property>
13 .
<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-->
18.
<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-conf iguration>

.

'

I

I
1
i

Q.) What are the Simple Hibernate Application Requirements?
-.

1 Entity class
2 . Mapping file(Required if you are not using annotations)
3. Configuration file

4. DAO class (Where we write our logic to work with database)
I

I1

Setting hibernate environment

i

I

I

1

I

'

;To work with hibernate framework we need t o add .jar(s) files provided by that framework to

j

(

I

our java application.

i

No framework-is installable software, it means we doesn't contain any setup.exe

'i When we download any framework, we will get a 'zip' file and we need t o unzip it, to get the required

jar files, actually all frameworks will follow same common principles like ...

1.

i

1
j

!

o

Framework will be in the form of a-set of jar files, where one jar file acts as main (We can call

!

this file as core) and remaining will acts as dependent jar files.

I

1

o Each Framework contain at least one configuration xml file, but multiple configuration files also

>

>

allowed.
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.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified Company
---

http://javabynataraj.blogspot.com
Page 10
9

i
1
j

1:
I

1

-

-

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
,

-

1'

is depending on your database. For example, if we are working with Oracle we need t o add ojdbc6.jar.

4.) W h a t are t h e Steps t o develop h i b e r n a t e applications?
Step 1: Develop persistent/domain/entity class f o r each table o f t h e relational m o d e l

-

Step 2: For each entity develop a mapping file
i

Step 3: Develop the configuration file

I

Step 4: Add hibernate f r a m e w o r k jar files i n t h e classpath

1

/

Step 5: M a k e use of hibernate API and p e r f o r m persistent operations

4.) H o w t o M a k e use o f hibernate API t o p e r f o r m persistent'operations?

I

STEP1: Create Configuration object
Configuration configuration = new Configuration();
STEP2: Read configuration f ~ l ealong w i t h m a p p i n g files using configure() rnethod o f Configuration Object

I

configuration.configure();

1
I

S'rEP3: Build a SessionFactory f r o m Configuration
SessionFactory factory = configuration.bhildSessionFactory();

!STEP4: Get Session f r o m SessionFactory object
Session session = factory.openSession();
I

STEP5: P e r f o r m persistence operations

I

I
1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
- --

--

http://javabynataraj.blogspot.com
11
Page 10-

Hibernate-Introduction
I

The Session interface provides methods t o perforni CRUD (Create Read Update Delete) operations o n
,.. the instances of mapped entity classes. Perform transactions if require while performing D M L :

i

:
I

operations. Session interface methods are ...

I

s;, 0 1-1

2:a:..'*
i. :3!:

-

l!l.:.el-tincl okjelzt

ses$;it:~n 1.19date1:s:
-

LJ:.~.cl~!it-~ci
object

L;

S

,

STEP6: Close t h e session

I

Final .flow will be ...

.8'
.

intl:~d a t a b a s e

:

.

' sit1 t h e ~ : l a t a b a s e

Sa:ssiul-1

TI-ansaction

Close Statet?lents

~ a r e s hi Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666, 23734842
An --I S 0 9001 : 2000 Certified Company
. .

http://javabynataraj.blogspot.com
12
Page 11

I

By Mr. SeltharRedcly
- .

Hibernate-CRUD- Application
.

-.

-

'

-A

4.) Develop Hibernate application, i n w h i c h w e can p e r f o r m account creation, retrieve, update a n d delete?
SQL Script
CREATE TABLE ACCOLIkIT (
ACCNO
NUMBER ( 5 ) IUOT NULL,
VARCHAR2 (20) NOT NULL,
NAME
NUMBER(8,2) NOT NULL,
BA L
CREATION-DT DATE
NOT NULL,
PRIMARY KEY ( ACCNO )

1
i

ACCOUNT TABLE
E: :-'.L

CREAT IOI I-DT

fiP541.07J ':74>:7illi
J . - .. - .
91:1U02 yellari.diis;

!

gDlli13 clierr-,!

E:i;5d$.69

5;'15;21:112

-ac(-iS?.?6
5,,'2!2l:l12

I

I
1

hibernate.cfg.xml
1 . <?xml version='l.O1 encoding='UTF-8'?>

2 . <!DOCTYPE hibernate-configuration PUBLIC

I

I

I

3.

4.

"-//Hibernate/Hibernate Configuration DTD 3.0//ENM
"http:/>hibernate.sourceforge.net/hibernate-configuration-3.0.dtdIT>

I

--- --

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified Company
----

-

p a 13
s http://javabynataraj.blogspot.com

I

I

i 1 I ! - ~.sekharit.Configuration.. . . -. <~nappLngre~~~ur~:~="c~~m/sekharit/hibsrnate/mappitig/Ar-cc~ur: t ... 20.. Hyderabad.il.. p a s s i i o r d " > t i q e r < i p r o p e r t .-. 21. .-. . . I j 14.~ ~ -. s c l l " > t r u e < / p r o p e r t ..23734842 An I S 0 9001 : 2000 Certified Company http://javabynataraj. ..:::. 29. 6. 20.?-I.. 1 26.set(session).SessionFactory sessionFactory. private static org.hibernate. !1 :. private static final ThreadLocaI<Session>threadLocaI = new ThreadLocaI<Session>()..d r i v e r -c l a s s " > G : ? z .=. . 30... 26. Satyam Theatre. 12.. ! i e c t i o n . 10.:. .printStackTrace(). -.!!~. . . j11 _ if (session == null) { session = sessionFactory. 25.. threadLocaI... -. .!-:-username">systi:n~<:prop~r~~-> < p r o p e r t . 1 i 23.'. ::!I:!?-" ::ci!!. 11. SekharReddy -.. public class SessionUtil { 8.l > .. e .-. 1- 1 } 19.. 24.-&. . 4.sr~. . import org. 18./ '. . autoU>update</pr-i>.. ~ : . . . Opp. ..-. ~~ I -\ By -Mr.on. } catch (Exception e) { e.::!?i:?ction.:. !' . tc < - < p r o p e r t .-. -. Ph: 040-23746666. : .-. . .-..= ":.Session. i-.hibernate.. I :.iava 1.cfg.ur.!?c:?. 1 . 1 27.... :. 22. ..buildSessionFactory(). . ! 15.configure( "com/sekharit/hibernate/config/hibernate.. OraclsDri~re~ 19.n-. SessionUtil..-2-"<::. .cfg. . - ~ ~~ ~ . . I! ' ! public static void closeThreadLocaISession() { 34. j 29.-:. . ~ J L ~ .--.yr*r- .c:ion....: . ..--.: - "< .xmI").: I - .. ... package corn.-.. sqll'>true</proper-c. P r o p e r :. ?I 33.com Page14 2 I I I !.blogspot. j 1 j I . : : > ~ = ~ !~. : <prop?rt:.-.. 21. 9.. i 24.u_ -. 5.- -~ - ~ .. i.2:. -.-. :!river.:: .t I:. } } . .. 27.. ~ > < p r o p e r t . 2. -. : .= -s q l . 17.%73. 25.r~. . </property> . import org. ------. -. . 28. Ir j I private Sessionutilo { } I I II public static Session getThreadLocalSession() { Session session = (Session) threadLocal.c o r n m e n t s " > t r ~ e < / p r ~ ~ ~ p e r t ~ . \ i try { ::: I ..openSession()..: n :. I I j 1 1 1 1 1 1 ! j I . ~" -. 22... .>..:. static { 18.< 1 .-y . . . ! ! 1 return session.rpei:t. 1 - 1.:I. -.-.. . Ameerpet. . Naresh i Technologies..... - </hibernate-configura:~311:.. ....YLT .hibernate.. .. 3. : Hibernate-CRUD-Application . sessionFactory = new Configuration()... 23... .. . .get().-.... % ...-! .hibernate. .p o o l s i z e n > l5.. : .I -..-. 16. -~. 7. . 1 ii 11 . </session-factor.. i 28.c3-. . . .-e="us.

tlireadLocal.close(). package com. Opp. public long getAccno() { return accno. 1 Naresh i Technologies.openSession(). Hibernate-CRU D Application ~ - ~~~. private Str~ngname.2. public class Account { 6. import java. 1 public String getName() { return name. 29.-- -~ . private Date creat~onDate. 1 7.sekharit. 1 5.Date. 10. 23734842 An IS0 9001 : 2000 Certified Company I p a g e ~15 ---' http://javabynataraj.close(). I I . . 1 1 public static Session getsession() ( return ses~ionFactory. 28.- . Ph: 040-23746666. ~ e l t l ~ a r ~ e d d ~ Session session = (Session) threadLocal.bean.get().accno = accno. 26. 27. -- Account. ) public double getBalance() { return balance. if (session != null) { session. 11. Ameerpet. private double balance.. 1 public void setAccno(long accno) { this. private long accno. 1 public stat~cvoid closeSession(Sessionsession) { if (session != null) { session. public void setName(String name) { this.set(nulI).ut~l.narne = name.java 1.- -- . Satyam Theatre. 1 1 .hibernate. 1 I 1 I I 1 I 24. - -- --- - By Mr. / 3.blogspot. 4. 8.com . 25. . Hyderabad. 9.

1 . Hyderabad.< ----.bean. public void serBalance(double balance) { this.com Page16 4 . I Account. -- . <column name="BALNprecision="8" scale="2" not-null="trueN></column? 14. public void setCreationDate(Date creationDate) { this.Transaction.. 46. <column name="CREATION-DT" not-nllll="true" ></column> 17.-- ~ 30..-.sourceforge. Opp.-- I Hibernate-CRUD Application . . -. 1 :: 1 import com.- .. 42. 39. 1 35.hibernate.bean.sekharit.- http://javabynataraj. </property> 12.hibernate. --. "http://hibernate. . 3. name=" + name } + "I".. hbm.. 32. 41. 38.iava 1. import org. </hibernate-mapping> 5. </property> 15. import 0rg. Ph: 040-23746666. Satyam Theatre.hibernate.O" encoding="UTF-8"?> 2. <property name="creationDate" type="dateM> 16. 11.5essionUtil. 45.\ ~~ - By Mr.-. <hibernate-mapping schema="SYSTEM" > <class name="com. 1 .0.Session.- -- I 1 - - 48. 37. ! 1 1 ! . .--. 8. </class> 19..util.23734842 An I S 0 9001 : 2000 Certified Company . <property name="balanceUtype="doubleU > 13. --- llaresh i Technologies.balance = bala~ce. public Date getCreationDate0 { return creationDate.cr?ationDate = creationDate.xml 1. 5. } @Override public String tostring() { return "Account [accno='! t accno + ". </property> 18.dtd" > 4. . 2.HibernateException. balance=" + balance + ".d d ~ .hibernate..sekharit.net/hibernate-mapping-3.Account. .U .- - - - -. -- ~ . <?xml version="l. /1 .Account" table="ACCOUNT"> <id name="accno" type="longU > <column name="ACCNOUlength="SU not-null="true" ></column> </id> <property name="nameUtype="stringM > <column name="IUAMEUlength="2OVnot-null="trueV ></column> 10. .ly.. import com. creationDate=" + creationDate + ".sekharit hibernate. Ameerpet. package com.. 44.blogspot.. --. ~ e k h ar ~ e..-\ 31. 4. .hibernate. 47. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.hibernate. AccountDAO. import 0rg.-- [--? .da0. 43.sekharit. - .O//ENU 3. } 1 1 1 40.S. . 33.-.

session. 27. Hyderabad. wi.e-ii-ii-l 9. } f~nally{ 53. 48. 14.getTransaction(). } catch (HibernateException e) { I 19. 35.getSess~on(). 55. 49.begin(). 33. bernate-CRUD Application . session = SessionUtil. return account. 20. 34. public void delete(long accno) { i I 7 1 1 1 I I 1 I I 1 I -- Naresh i Technologies.getSession().- --- . session = SessionUtll. } 57.getTransaction(). } catch (HibernateException e) { ( 51. Satyam Theatre. 13. session. account = (Account) session. p u b l ~ cv o ~ d~nsert(Accountaccount) { 28. session. Sess1011session = null. Session session = null.23734842 An IS0 9001 : 2000 Certified Company - - PagT5http://javabynataraj.save(account). } catch (HibernateException e) { 36.getSession(). .get(Account.rollback(). e. 24. 37. 1 1 23.getTransaction().By Mr. 22. e.getTransaction().comrnit(). Opp. beg~n().- .52. } f~nally{ 39. 15. try { 31.getTransact~on(). 1 40.class. sess~on. session. Session session = null. 10. pcrbl~cclass AccountDAO { 3 1. I 32. Ph: 040-23746666. 45. 38. ( ~ u b l l Account c get(long accno) { 12. SeltharReddy Hi.getTransaction(). Ameerpet. 58.cornm~t(). try { 46. } I 41. SessionUtil.com 17 . I 17.update(account). 50.cl~seSession(session).printStackTrace(). 30. -. 43.closeSession(session). session.rolIback(). . 18. SessionUtil. } f~nally{ 1 21. session. session.blogspot.printStackTrace(). } 42. session = SessionUtil. 1 47. j 25. 1 29. e printStackTrace0. 54. 1 56. try { I 16. p u b l ~ cvoid update(Acc0unt account) { 44. SessionUtil.closeSession(session). accno). } 26. Account account = null.

iava 1.setAccno(90003). 1 i I I1 / I AccountService..getBalance()). 25. Account cAccount = new Account().hibernate. 14. Account uAccount = new Account(). System.insert(cAccount).set~ame("sekhar").AccountDA0.. // Retrieve Account 13.class. 32.Account.println("Creation Date: " + rAccount. 5.getAccno()).get(90001). 27.seltharit. } finally { SessionUtil.hibernate. uAccount.setName("sekhareddy").out.printStackTrace(). 22.out. Ph: 040-23746666.-- - -- -.util.out. 1 ::: 1 1 1 I Naresh i Technologies.. .beginTransaction(). 19. 10. 8. 26. Opp.out. Satyam Theatre. System.-. transaction = session.out. transaction. -. import corn.println("Account details .dao.. cAccount.getName()).Date. package com. 30. 9.--.-- -. e.-.getCreationDate()).out.commit().println("Account created successfully"). public class Accountservice { public static void main(String[] args) { AccountDAO dao = new AccountDAO().delete(account). Account rAccount = dao. Svstern.get(Account.rolIback().setBalance(6899). 31.println("Accno : " + rAccount.service..com Page18 6 .sekharit. cAccount.blogspot."). // Create Account 20. 12. - -- . - B Mr.getSession().-- . 17. import corn. accno). 6. import java. cAccount. 11.setCreationDate(new Date()).hibernate. 3.println("Name : " + rAccount. session. Tramaction transaction = null.sel~harit. dao. c~ccount. } catch (HibernateException e) { transaction. // Update Account 29. 24.23734842 An IS0 9001 : 2000 Certified Company --- http://javabynataraj. 18. Account account = (Account) session. Systern. System.println("8alance : " + rAccount. 28. Hyderabad. 7. try I session = SessionUtil. uAccount.setAccno(90005). Systern. Ameerpet.closeSession(session). 23. 21.bean.Sel<harRecldy Hibernate-CRUD Application -- Session session = null.

. <?xml version='l.. Sel. 33.\li. . ! Naresh i Technologies.jar lib . / > . c<clbclJ. i. } ... Ameerpet.. "-//Hibernate/Hibernate Configuration DTD 3...-*.cfg. . <session-factory> <property. 1..c c.) R e w r i t e t h e above application. 1 : 1 -- I . 38.'21:1!:: 9l:ll:lOj 1 45i10 j!Z?jLI:l]z 6Sgg 5 2 9 j i C 1 1 2 Q.utiI ' . .1.. 42.3 Annctation': F...xml . hibernate. 41... .. 9. * cctn. H i t x r n a t e 3.3 C n r e Libraries -- . <!DOCTYPE hibernate-configuration PUBLIC 3.~a ..O' encoding='UTF-8'?> 2 . System..update(uAccount). using a n n o t a t i o n s instead o f m a p p i n g file? d . Hyderabad..sourceforge.lE E:AL CREhT 101I-UT ? I:i..setBalance(4500).lanagel Hitlel-nate 3.blogspot. Ser-~ian!JtiI. .out..23734842 An IS0 9001 : 2000 Certified Company Page 19 I http://javabynataraj. -- . -- -- By Mi-. . } After Execution ACCOUNT TABLE : . 43.dtd"~ 5. . .Hibernate-CRUD Application --- I--..delete(90002). LI ~ i Rj e f e r ~ t i c e dLihrariel: 080 3 .rtkb~arit. System. . :. . .. JRE S y . . Opp.. ?:-eddy ~e\..: :. 35. 8. 6.tllll-edjj' !21:11:105 5el:hal- t 69541.. 37. // Delete Account dao.~a~.com ! ...:a>. I:. . "http://hibernate.-.setCreationDate(new Date()). dao. .03 5: 29.ha~-Reddy .i r-:.println("Account is deleted successfully"). Satyam Theatre.. 40.O..t Entit!.net/hibernate-configuration-3.10 Il.0//ENn 4. 36. <hibernate-configuration> . 39.hih~rnatr.println("Account updated successfully").. . uAccount. ~ t i i Li ~i b r a y . .a::... Ph: 040-23746666. uAccount.-J. . .out.:. . 34.

DATE) 48. 63. \ x. j I I I . 23734842 An I S 0 9001 : 2000 Certified Company i I _ _ _ _ 1 http://javabynataraj. 57. public Date getSreationDate() { 50. ! I \. . Ph: 040-23746666.--. return "Account [accno=" t accno + ".. this. h . balance = balance. @Column(name = "NAME". 29. . 36. . I i - I I! AccountService. 43.iava ---Same As Above--- 1 / /r ' - I -- I Naresh i Technologies. length = 20) 30. .. 55.blogspot. 41. 32. I .creationDate=" + creationDate + ". :I1 \- I. Ameerpet. } 56. this.. nullable = false. 53. 51. } 28. 45. ~. I I \ 1 / . ~ i1 - Hibernate-CRUD Application / - - -.accno = accno. Hyderabad. public String getName() { 31.balance=" + balance 60. I* ! 1.. } 37. \ \ .hbm.. 1 i- 1. nullable = false.{ 54. @Override 58. return balance. 38. - By Mi-. return creationDate. Sekhal-lieddy. @TemporaI(TemporaIType.'%-*au#A&. } 33. :.xml ---NOT REQUIRED--- 'A . return name. nullable = faise) 49. Opp. 1 Account.. -*=--&= -. . AccountDAO.. } 46. 1 24. this. Satyam Theatre. 34.java ---Same As Above--- ! I. scale=2) 39.I i 1 1 1. public void setName(String name) { 35. @Column(name = "BAL". 27. . } 42. precision=8. this. public void setCreationDate(Date creationDate). } 52. 25. 47. l~ i "I". i -. } 62. ! . .creation[>ate = creationDate. name=" + name + 61. public void set~alance(doublebalance) { 44.Lcas* ! j ' 1 ! ! I : 1 j i I 1 ) 1 1 1 I I 1 I i 1 1 1 . public double getBalance() { 40. I ? .name = name..com Page20 9 \ . public void setAccno(1ong accno) { 26. @Column(name = "CREATION-DT".-: ~' 23. public String tostring() { 59. I . t ".

hibernate.Conf~gurat~on". 1 .hibernate. } catch (Throwable ex) { I ! System. - -. 1 } catch (Throwable ex) { I System. 1 I I Naresh i Technologies. I Code snippets .cfg. 4 SO.hibernate.Configuration. 1s marked a s "deprecated".23734842 An I S 0 9001 : 2000 Certified Company Page 10 http://javabynataraj..- H ibernate-CRUD Application ---- B v MI-.err.I - The code is still working.---." throw new ExceptionlnlnitializerError(ex).buildSessionFactory(). Ameerpet.-- -- -- .The type Annotationconfiguration is deprecated I Problem I Working with Hibernate 3. - I + ex).cfg.AnnotationConfiguration.6.buildSessionFactory(). Satyam Theatre..err.cfg.blogspot.cfg AnnotationConfigurat~on"is deprecated. ts import org.-. just keep displaying the deprecated warning message.- --- - - ." throw new ExceptionlnlnitializerError(ex).configure(). + ex)..- -.6..println("Initial SessionFactory creation failed.hibernate.cfg.. you can safely replace your "AnnotationConfiguration" with "Configuration1' class. "org..com 21 . private static SessionFactory buildSessionFactory() { try 1 1 return new AnnotationConfiguration().hibernate. private static SessionFactory buildSessionFactory() { try 1 return new Configuration(). and all its functiona!~tyhas been moved t o "org. is there any replacement for "AnnotationConfiguration" ? I I i Solution Q ! I I ! I In Hibernate 3. ~ e l t h a r ~ e c l d v - Hibernate . org. noticed the previous "org. Opp.Annotat~onConf~gu~-at~on". -- -- --- .configure().println("Initial SessionFactory creation failed. / I. Hyderabad. Code s n i ~ ~ e.. Ph: 040-23746666.

Column.. Hyderabad." .. @Entity 12.AnnotationConfiguration. 11.SessionFactory sessionFactory.buildSessionFactory(). importjavau. 4. .persistence. . 4... 2. . .. 1 1 1 . Naresh i Technologies.ld.Session.persistence.. 18..hibernate. 17. \ r I i1 1 1 . .. .hibernate. . . private static org. . . 7. import javax. .xmI").. 15... @Id ' 1 9 . 8..util. . 17. 4 ' - I A Account" /> ' 5. ..Table. 16. package com. Ameerpet.. - % Account.configure( "com/sekharit/hibernate/config/hibernate. 16.. . By Mr. 14....hibernate.persistence. } catch (Exception e) { e. . . 13. public class Account { 14.. 10. Opp..I I static { try { sessionFactory = new AnnoationConfiguration()... return accno....persistence.. @Column(name = "ACCNO". importjavax. import org. private String name. . 3. 1 9.---. ..23734842 IS0 9 0 0 1 : 2000 Certified -Company An . . 2. . .. import javax. import-java. 8.java 1. " I } I .. .. I I private static final ThreadLocal<Session> threadLocal = new ThreadLocaI<Session>(). . 13..printStackTrace().hibernate.- _-- _ __ .iava 1. import javax.sekharit.. nullable =true. . 6.. ' 10. ' ! : .Entity. length=5) 20.--- Hibernate-CRUD Application - - -.. .sekharit.persistence.com ~a g e22 8.. 3... private double balance. . .. 21.Date. I .. 11. Ph: 040-23746666. .. .--..hibernate. package com..i .. private Date creationDate. 15. Satyam Theatre.cfg. http://javabynataraj. 5... . private long accno.TemporalType.persistence..cfg..' . 1 ..... .. 1 7.bean. import org. . @Table(name="ACCOUIVT") ...blogspot.' .. public class SessionUtil { 9.. 18. import javax. } :I - I . ___a -. 12. .uti1. -.Tempora1. public long getAccno() { 22.. I 6. - -- -- - - -- - . SessionUtil..SeltharRedciy -..

password. Opp. Ameerpet.blogspot. Hyderabad.xml I I I I I -- I I - 1 I 2) show-sql: if the 'show-sql' value is true we can view all the hibernate generated queries in the console.com : .pool-size: Used t o configure hibernate provided connection pooling in hibernate. Use the existing schema > If i t s value is 'create' while running the application hibernate will drop t h e old schema and it will create the new schema.Hibernate-Arcl~itect~~ral Elements ' ' .cfg. Ph: 040-23746666.datasource"~myDataSourceI\lame~/property~ I 9 Hibernate slupports default connection pooling but which will not be used in projects We use always 1 I server provided connection pooling.auto: It has t w o values a. so that easy t o read <property name format-sqln>true</property> 5) hbm2ddl. update I a.cfg.------- P a g23 e1 http://javabynataraj. 3 This xml file used t o specify locations of mapping files/Entities I > In projects we don't give the database details(ur1. (Based o n HBlVl file) Naresh i Technologies.) 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 Case 2: table exists i Drop the existing schema and create a new schema based on the mapping file configurations I b. Satyam Theatre.ery. <property n a m e = " s h o w ~ s q l " ~ t r u e ~ / p r o p e r t y ~ 3) use-sql-comments : To add SQL comment t o the SQL query generated by Hibernate <property name=" u s e ~ s q l ~ c o m m e n t s " > t r u e ~ / p r o p e r t y ~ 4) format-sql : Format the SQL ql.) Update: If its value is update while running the application Case 1: table doesn't exist I Create a n e w schema based on t h e mapping file configura.23734842 An IS0 9001 : 2000 Certified Company . Q. username. I) connection. create or create-drop b. we give JNDl name of DatatSource.xml (configuration file)? I I .tions I i Case 2 : table exists - 1 I I -. I instead of that.) Explain more about hibernate. driverclass) in the configuration file. <property name="connection.

I I I 1 I. Hyderabad. hibernate will check for schema existence. Ph: 040-23746666.) What do you know about dialect in Hibernate? P Dialect class is a simple java class. \ --- Naresh i Technologies. Satyam Theatre. If schema doesn't exist it will I I create the new schema.xml file.cfg. If you want t o shift from one database t o another just change the Dialect class name in hibernate. 1 9 All 1 9 Hibernate supports almost 30 dialect classes.com Page24 2 . which contains mapping betweerr java language data type and database data type.23734842 An I S 0 9001 : 2000 Certified Company -- 1- http://javabynataraj. Opp. Q. i 1 1 I ! Dialect classes must extend 'Dialect' (abstract) class 9 If we want we can write our o w n dialect by extending Dialect class I Dialect class i s used convert HQL queries into database specific queries. Ameerpet.I 3 If its value is 'update'. If the schema already exists it uses the existing schema for persistence operations.blogspot. / P i I Dialect class contains queries format for predefined hibernate methods 2 Hibernate generates queries for the specific database based on the Dialect class.

Opp.blogspot.hibernate.hibernate.SybaseAnywhereDialect I I I 1 org. > <id> tag property corresponding column can be primary key or non-primary key in t h e database > In mapping file class names and property names are case sensitive.) Explain m o r e a b o u t Hibernate mapping file? > Each hibernate mapping file must contain only one <id> (or relevant t a g <composite-id>) > Java object identified uniquely by t h e <id> tag property.dialect.dialect.MckoiDialect I I I lnterbase org.hibernate.dialect.dialect.DB2400Dialect DB2 05390 org.PostgreSQLDialect 1 MySQL I org.2-.Dialect oracle l o g org. Satyam Theatre.dialect. But Table names and column names are n o t case sensitive.dialect.Oracle9.dialect.hibernate.dialect.hibernate.dialect.hibernate.hibernate.SybaseDialect > Sybase Anywhere 1 I Microsoft SQL Server I I .lnterbaseDialect 1 ! Pointbase org..MySQL5lnnoDialect I Oracle (any version) I ' 1 1 org.dialect.hibernate.dialect.hibernate.hibernate. Ameerpet.te.MySQL5Dialect MySQL with InnoDB 1 org.hibernate.HSQLDialect i 1/ Mckoi SQL 1 1 I org.dialect.DB2390Dialect PostgreSQL org. hibernate.hibernate.hibern.dialect.SQLServer2008Dialect ' 1 I I org.dialect.~~~server~ialect TI Microsoft SQL Server 2008 I org.com 25 .hibernate.hibernate.hibernate.dialect.Hibernate-Arcl~itecturalElements - DB2 AS1400 org.FirebirdDialect I .FrontbaseDialect Firebird org. Ph: 040-23746666.dialect..23734842 An IS0 9001 : 2000 Certified Company -- ! 1 I ! PTe. Naresh i Technologies.dialect.hibernate.hibernate.ProgressDialect I org.lngresDialect Progress I I -1 1 org. .A I I I II 1 Q.Oracle8iDialect oracle 9i org. ! 8 HypersonicSQL I I I- I I lngres 1 org.dialect.dialect.dialect.http://javabynataraj.PointbaseDialect I FrontBase org.hibernate.hibernate.SAPDBDialect I SAP DB I / org.Oracle10gDialect 1 Sybase 1 / org.dialect. Hyderabad.

- i Ii P When the property name and column name both are same we no need t o give 'column' a t t r i b u t e r When the Pers~stentclass name and table name both are same we no need t o give 'table' a t t r ~ b u t e r Generally we write one mapping f ~ l eper one domain object. Ph: 040-23746666. . some database places all tables in a different "catalogs".com Page 26 4 :. .) Explain about annotations which are used in our application t o m a p entity t o table? P In our examples if we observe. If we want we can specify this in <class> tag of the mapping file Instead of that we can write package name separately using "package" attribute of <hibernatemapping> tag P 1 I I I I \ \ I In the mapping file we no need t o map all t h e properties of the entity and all the columns of table. ~ Mr. Some database places all tables in a different i 9 In mapping file we write fully qualified name of the entity class in "name" attribute of <class> tag. - ~ tectul-a1 Elements j Hibernate-Archi .. ~ ..-~ . As per our requirement we configure required properties of the entity and columns of the table Q. . I r Databases have different ways t o organize i t s tables.~ -- ~ . . Hyderabad. . Satyam Theatre.blogspot. Opp. ~ ~~ . "schemas".. Per each class mapping we need t o write one <class> tag.D . But i t allows writing multiple objects mapping information within the same mapping file. Ameerpet. we used the following annotations o @Column Naresh i Technologies.- - ..SekharRecidy -La. . ~ ' .23734842 An IS0 9001 : 2000 Certified Company w e - http://javabynataraj.

cfg.(But it will become Hard coding.All the above annotations we are taking from java...lPA.blogspot. Hibernate is a specific API. We prefer t o use . Hibernate. This paclcage is from . - I . -. Hibernate-AI-chitectural Elements .23734842 An I S 0 9001 : 2000 Certified Company .addResource("Bid.pppp-. . Some of famous implementation of ]PA are Open.hbm. If we use JPA annotations we have t o flexibility t o change the implementation vendor without changing application code.lPA annotations. . .IPA(Java Persistence API). Ph: 040-23746666. - Adding Entities(anrl0tated persistent classes) t o configuration object programmatically I I. -~ .. where as ]PA is a specification. 4. http://javabynataraj.xml") . Finally all these variables are grouped and create one high level hibernate object called SessionFactory object. . its not the implementation.. Actually this paclcage is not the part of hibernate API. .IPA is an APl(from SUN).)What is Configuration object? > - 1 I . - .~ekl~ai-~ecldy . Reason for this is. . so not advisable) 1 Programmatic configuration I Adding mapping files t o configuration object programmatically 1 Configuration cfg = new Configuration() .I o @GeneratedValue o @Temporal . But we don't prefer t o use hibernate given annotations.xml" which is located in "classes" folder 9 If we want t o change the file name or i f we want change the location of "hibernate.etc. Opp.xml").persistence package... Naresh i Technologies. . Ameerpet.xml" then we 1 need t o pass user given configuration file name (along with path) t o "configure()" method of Configuration class 1 P Configuration object Stores the configuration file data in different variables. I I I -- P So Configuration object only meant for creating SessionFactory object > If w e want w e can provide the configuration information programmatically.. . Satyam Theatre.- ~ 8 - .cfg.& lr ~r. Eclipselinlc .hbm. Hyderabad. . Toplink Essentials. > These annotations also given by hibernate. . i ' > for ]PA.addResource("ltem. There are multiple implementations are there Object Oriented representation of hibernate configuration file along w i t h mapping file is known as Configuration object 3 By default Hibernate reads configuration file w i t h name "hibernate. without writing configuration file. . .. _n x .com Page 27 5 . /.

dialect. set System properties using java -Dproperty=value.- - Naresh i Technologies....ltem. - -. - - . Ph: 040-23746666..- . --- -. . . .properties is t h e easiest approach.auction.. This is not the only way t o pass configuration properties t o Hibernate. Connections.JI.. SessionFactory object provides lightweight Session objects.ltem.addClass(org.com ~ a g 28 e6- - .cfg. .how many SessionFactory objects I can use ? ASessionFactory is pretty heavyweight. .Properties t o Configuration.class).hibernate. . . Some alternative options include: 1. . SessionFactory is also responsible for second-level caching.. so. Satyarn Theatre..auction..Bid. --- - -. Arneerpet. Configuration cfg = new Configuration() .. MI-.class) .addClass(org.) What i s SessionFactory? SessionFactory is an interface and SessionFactorylmpl is the implimented class It is factory of Session objects It is heavy weight object t h a t has t o be created only once per application. - .. - - -.addClass(org.setProperty('hibernate.SekharRectciy . ~.hibernate. 3.connection. ..class) .- - - .auction.addClass(org. Opp. we recommend creat~ngone and caching it in a singleton type of way. .order~updates".Elements .- - - - - - - . -. Q. If you want t o get started quickly hibernate. 4.auction. - - Iiibel-nate-AI-chitectul-a1 ----.. m..diaIect".) In one appl~catlon.utiI.cfg. -.) Why SessionFactory is heavy weight? P SessionFactory encapsulates Session objects. Lets create it only once using Util/Helper class SessionFactory is a Thread safe object. .setPr~perty("hibernate. "java:comp/env/jdbc/test") . ~ . 2. Hyderabad. - . ---- . Pass an instance of java. cashing and mappings.-~-. I Q. .blogspot.Bid. "true"). Then.- - - - -.23734842 An IS0-9001 : 2000 Certified Company -- http://javabynataraj.setProperties(). > Q. So if you are using multiple databases then you would have to create multiple SessionFactory objects..Configuration i s intended as a startup-time object t h a t will be discarded once aSessionFactory I S created. Place a file named hibernate. Include <property> elements in hibernate.class) .setProperty("hibernate.I 1- I -- - .xm1 (this i s discussed later). i i ) To add hibernate properties t o Configuration object programn~atically Configuration cfg = new Configuration() . --.properties in a root directory of the classpath. Hibernate-properties. The org.X.hibernate.hibernate.hibernate.. you can create as many Session objects from it as you like.MySQL11~noDBDialect") . "org.- - .datasource". You need one SessionFactory object per database.. SessionFactory is not singleton. .hibernate. --.

beginTransaction(). . Session object is called persistent manager for the hibernate application.. ) catch(Exception e) { Naresh i Technologies. I -1 I . t o release all the resources such as associated objects and wrapped JDBC connection. I > It has convenience methods t o perform persistent operations. o Transaction transction = session. . .) What do you know Session object? r Session is an interface and Sessionlmpl is implemented class. o transaction.-.. i > > Transaction object is unique per session object..-.commit(). {un successful transaction ending ) > Default auto commit value is false in Hibernate..23734842 An IS0 9001 : 2000 Certified Company ..com . 7. Ph: 040-23746666... Transaction t x = null. 3. Ameerpet. ~t has t o be closed.--. ..openSession(). Opp.Hi bernate-Architectural Elements Q.".blogspot.. Using Session Object we can create Transaction object in t w o ways.ro!lback(). tv { tx = session. 6.getTransaction(). Transaction interface defines following methods t o deal w i t h transactions.--. o Spring Transaction - Sample transaction code is as follows . --.. ... short-lived object > It Wraps a JDBC connection r The Hibernate Session operates using a single JDBC connection which can be injected by the r hibernate while constructing session object. 4. o Transaction transaction =Session. - 4.. // DML operations tx. Hyderabad. . 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. r - -. 2. commit(). --- - Page 29 7 http://javabynataraj.) What i s Transaction ? Transaction used by the application t o specify atomic units of work (Transaction management).beginTransaction(). r Default auto commit value is true in JDBC 3 In hibernate even t o execute one DML operation also we need t o implement Transactions. { successful transaction ending ) o transactin.begin() {Transaction beginning) o transaction. I 1. - I I 5..- - Session = sessionFactory. both are given in orghibernate. Satyam Theatre.. Hibernate supprots > o JDBC Transaction. . It i s a single-threaded(not-thread safe). o jTA Transaction.

....mEC' C'scatc TJses Scssiorl Factor?. . Q..) Why we have written SessionUtil class? 1 I .SC .. Give the driver name (logical name.... which i s used t o refer this configuration) I 1 I 1 Naresh i Technologies. --. so we should make one SessionFactory per 1 i Mr.. 0 Using Util /Helper class w e read the configuration file only once and we create one SesisonFactory ..c. Satyam Theatre. ! I . ......... - .... 0 SessionFactory is heavy weight and it's n o t singleton.-- . Hyderabad.ypl..- i A DAI~I~:.. I i'i. Select driver template as oracle(thin driver)... O When w e choose t h e new option.Se1tharRecldy -. Now we need t o fill t h e I > following options in the dialog box. .... In the DB Browser window right click on !: > 1 / I / iL the white place and select "new " option.... I Hibernate complete architecture Read ! . Ph: 040-23746666. and we are providing fac~lityt o get session object and t o close session object..com Page30 8 I 1 J .. - -- ..-.1 1 Hibernate-Architectural Elements C i ! i s - When some common logic i s repeat~ngacross the rnult~pleclasses of an application..... if we are using oracle database.cation 3 ' /I 1 1 1 Creates . _ ..blogspot.1-:vL<cr\..-...... I / --=A...... Opp.i - ..... I i database. ~t IS better t o move the common logic into some util class.... .. Where ever we need that common logic we make use of util class... Ameerpet. I configure a database driver in eclipse: Launch o r open MyEclipse Database Explorer prospective....23734842 An I S 0 9001 : 2000 Certified Company http://javabynataraj.... it will launch database driver dialog box.. Session - - class --...-.

i Select t h e database driver which w e have created and r i g h t click o n i t and select open connection i It will display a dialog box. Fill t h e required username a n d password. t h e n se!ect classes. Opp. Ph: 040-23746666.Hibernate-Architectural E l e i ~ ~ e i ~ t s I 3 Give the connection url.jar file I- Click on save password > CIick on finish I ! Hibernate Reverse engineering > Open Myeclipse database explorer prospective. Ameerpet.23734842 An IS0 9001 : 2000 Certified Company Page 31 9 http://javabynataraj. > > w e need t o select t h e "java source folder (src)" select t h e java package and click on finish Naresh i Technologies.blogspot.com 1 1I . > Click on Add Jars button. Hyderabad. 3 Give the username and password. Satyam Theatre. r Select appropriate schema where o u r tables are stored > Right click o n t h e table and select "hibernate reverse engineering" 'i The above operation will display a dialog box i n t h a t I I 1 -.

: Session.lock() j Session.- Transient State --A -- -- Session. Detached State Life cycle\object description / II .'. Hyderabad.(.merge() f i 1 I : Session.update() !i Session. Persistent state 3. Lifecycle .save() . uniqueResult() B Session. 1 Object associate w i t h session Transient state NO Persistent state YES I Detached state : . Opp. I Hibernate-Persiste~~t Object.persist() : arb age collection 1..clear() : Session. (-"]new : 'L- ! 1i Detached state - -instance . Transient state 2.saveOrUpdate() t Session. ' 1 I ! /. Satyam Theatre. Ph: 040-23746666. Session.scroll() Session.-. I 1 ! I I Persistent Object has three life cycle states 1.saveOrUpdate() i Sc.evict() : Session..merge() ~arbage'collection Session.iterate() Session.replicate() .23734842 An IS0 9 0 0 1 : 2000 Certified Company http://javabynataraj.. Object present i n t h e database YES I N0 YES Note: - 3 Object is associated w i t h session means object reference is available to the session object 9 Object present in t h e database means object identifier value i s available in database primary key column (Non identifier column values are n o t matter) Note: We can find the different diagrams for the persistent object life cycle as follows Naresh i Technologies.SekharReddy - - . Persistent Object life cycle I I .delete() Session.blogspot.ssion.get() I I j Session.close() 1 i i Session. i .load() Session. Ameerpet. .com 1 Page32 ." - Mr.

!. - . . l "Hlt:~prr!atp iij /by IBallet' 4 G King 1 \ '-I 1 ' - .i' Ada!:ltpd . -..... I.\ --_ ..blogspot. 23734842 An IS0 9001 : 2000 Certified Company Page 33 2 http://javabynataraj.I Hibernate-Persistent Object -Lifecycle --. I i' 1 1 lrjl.\ <.1.. .' I 7 4 .. 2. . I --_--__-- ------ I .--/ .. -.2.A -:--tdL.e~ .~: i.!. ::. Ameerpet.%. . Hyderabad. 31il.. ----from 4:ti:y.A. r - MI-. - D~tached ... 2 ~ [ :$?::!...- ..com I 1 .. I '.--- by-------- .) a ~ ( c! l ~ .-..I._.~~ I'~I._ -_ I ..- . - /~..I~ ~ ! ? r a t .~i:l~~....P ~ ~I~~ ?PI'~~~IPI'I! I '-7r.I Naresh i Technologies. Satyam Theatre. 1 2 -.lill.SekharReddy -... Ph: 040-23746666.. Opp.p:#:111r .IcI(. /_/- IT^^-^.: .-. I!./#..-.

w -.. . account.setAccountld(1003). account. 23734842 An IS0 9001 : 2000 Certified Company - http://javabynataraj. Hyderabad. -- Naresh i Technologies.. --. I Hibernate-Persistent Object Lifecycle I - I . Account account = new Account(). -- -I _ m _ _ < - . 2. Ph: 040-23746666. when i t is not associated with session and not present in data base. ~ e k h a -r-~ e d d T - S .set8alance(l500). Opp. Satyam Theatre. Example: Table ACCOUNT 1 ACCNO / NAME 1 1 kesavareddy 1001 1002 Sekhar / BALANCE 1 1500 1 2000 I I i 1 Application code: 1. Ameerpet. 4.r .com Page34 3 --- . 3.- % i Transient state: An object is said t o be in transient state. So we can say that account object is in transient state..setName("yellareddy").. account. ..blogspot. -- . ~ . > In the above example account object is not associated with session and there is no matching record in the ACCOUNT table.

object is not synchronized w i t h record.getTransaction()begin(). So we car: say that account object is i n persistent state. when it is associated w i t h session as well as object present 3 1 in database. Ph: 040-23746666.e.com Page 35 4. P Changes made t o objects i n a persistent state are automatically saved t o t h e database without invoking session persistence methods ' I USE CASE: Explains Persistent state 1 Session session =SessionUtil.' H i b e r n a t e . Opp. 1. ! P In the above example account object is associated with session and there is a matching record in ACCOUNT II P I n this state object is transactional. Satyam Theatre.class.e. 1. IVlodifications done t o entity. session.23734842 An I S 0 9001 : 2000 Certified Company - - http://javabynataraj. . Ameerpet. Hyderabad. ( Persistent state: An object is said t o be in persistence state. doesn't save into database.1002).e. 1.Hibernate i s NOT aware t h a t it exists Naresh i Technologies.blogspot.~ e r s i s t e lObiect ~t Lifecvcle i 1 In this state object is non-transactional. t h e object is synchronized with database record. ! // 'transient' state . I .' Example: Table i ACCOUNT ACCNO ' ( 1 NAME 16iiEF kesavareddy ( ~ 1500 - y Sekhar I ' I Application code: Account account = (Account) session. 1 table.getSession().get(Account.

--.save(account).println(account. and no longer manages the object I session.getTransaction().-.- Mr. // notice the Java object is s t i l l alive. or goes out of scope I System.- - - 1 Hibernate-Pel-sistei~tObiect Lifecvcle / -- -- . account.getBalance()).delete(account). Ph: 040-23746666.setBalance(500).setBalance(500).account is returned i n a 'persistentJ state Account account = (Account) session.setName("cherry"). 1 // retrieve account with id 1.- http://javabynataraj.getTransaction().SekharReddv Account account = new Accoui. account.com 36 Page 5 1 .-. Satyam Theatre. 1).begin(). 3.. 2. Hibernate deletes the // database record. sess~on.getSession(). // modification is ignored by Hibernate since it is in the 'transient' state account.out. Ameerpet.blogspot.get(Account.. Example: Table ACCOUNT I ACCNO I N A M E 1 1001 I 1002 I .. . // stays alive until developer sets t o null.class.comrnit(). // commit the transaction session. i // commit the transaction session... Account account = new Account(). -. 1 ! //transition t o the 'persistent' state. // transition t o the 'transientJ state. 1 // modification of the object will automatically be // saved because the object is in the 'persistent'state account. Opp. Detached state: An object is said t o be in detached state.t(). IVaresh i Technologies. Hibernate is N O W 1 // aware of the object and will save i t t o the database I session.getTransaction(). though deleted from the database. Hyderabad.co~nrnit(). kesavareddy / Sekhar I I BALANCE 1 / 15001 2000 I J Application code : 1. when the object is not associated with session but present in data base. 23734842 9001 : 2000 Certified Company An IS0 . I USE CASE: Explains Transient state / Session session =SessionUtil.setAccountld(1004).

. account ..Selt11arReddy -- -- L" -...... As session i s garbage collected..----A - account. 5..... ... 9...... Satyam Theatre. // NOLVthe account object is said t o be in persistence state 4.. . .- Session .. / / N o w the account object is said t o be in transient state 6. Ameerpet...23734842 Company An IS0 9001 : 2000 Certified -.. .... .. .. account object is moved t o Detached state from persistent state..setBalance(2100).close() method. . i f we try t o perform some modifications t o entity object those changes will not be stored into database.. .> __ ... I -.. session. I I ..... i LOU2 - lOUJ // Now the account object is said t o be in detached state. Hyderabad..com Page 37 6 ....... '.... . Naresh i Technologies...... 7...Hibernate-Persistent Object Lifecycle I ~~-~~ Mr. Opp.. ... - I / => In the above example after callingsession.. ....save(account).-- http://javabynataraj. ...blogspot. ... ... .. Ph: 040-23746666.

/ Session session1 =SessionUtil. . 11 // c o m m i t t h e transaction I .. ' => In this state object is non-transactional.SeltharReddy .com 38 page-7- . 1). . Session2. b u t t h e account still represents a r o w i n the database account. account is returned i n a 'persistent' state Account accoilnt = session./i . -~ Hibernate-Persistent -. ~ .- ~ .get(Account.close(). i // c o m m i t t h e transaction 1 session.. . Naresh i Technologies.. 23734842 An IS0 9001 : 2000 Certified Company .~ p-p-p-.ii_-. ~ . Means object is not in sync with database. Hibernate no longer manages t h e object Sessionl. // re-attach t h e object t o an open session. -_ . Hyderabad. delete().setBalance(500).. j' " Saving Changes t o t h e Database r3 Session -- methods d o NOT save changes t o t h e database save(). i I iI I I / USE CASE: Explains D e t a c h e d s t a t e // retrieve account w i t h i d 1. . .account is returned i n a 'persistent' state Account account = sessionl.. i // I i // transition t o the 'detached' state.-. So Changes made to detached -.commit().. // modification is ignored b y Hibernate since it is i n t h e //'detached1 state. . 1).. objects are not saved t o the database. Satyam Theatre. --Object Lifecycle -- ~. 1 I // modification is ignored by Hibernate since it is i n the //'detached1 state. update(). Ph: 040-23746666. / retrieve account w i t h i d 1.setBalance(500). // transition t o t h e 'detached' state.class.-.class. returning it t o t h e //'persistent1 state and allowing its changes t o be saved t o t h e database Session session2 =SessionUtil. Ameerpet....getSession(). Opp.blogspot. _..update(account).----.getTransaction(). Hibernate n o longer manages the object session..getTransaction(). session2.close().- http://javabynataraj.get(Account.-.. . 1 I i I USE CASE: Explains D e t a c h e d state .getSession().. Mr. -. begin(). . but the account still represents a r o w i n the database account.

. I 1 - //flushes changes t o t h e database and c o m m i t t h e transaction session.getSession()...commit(). .begin(). The Persistence Context ' i 4 Each Session object contains one Persistentcontext.commit(). It might be containing t h e follow things: Graph of managed persistent instances List of SQL statements t o send t o t h e database i I ' .--- -. . .session. ~.save (account).transaction.getTransaction(). Ph: 040-23746666.-- -. Session.com rage tr39 .session.! ~ l u s h i n tgh e Context Submits the stoied SQL statements t o t h e database Occurs when: .getTransaction(). // 'transient' state . Opp.commit() is called 1 . Naresh i Technologies.Hibernate is NOT aware that it exists Account account = new Account(). Hibernate is NOW // a w a r e o f t h e object and //schedules t h e insert statements t o create t h e object i n t h e database session. all the queries will be pushed t o t h e database ..flush() is called explicitly 1 USE CASE :Scheduled Changes ( Session session =SessionUtil. 23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. Mr. i a These methods actually SCHEDULE changes t o be made t o the database O n c e Transaction committed. Ameerpet. //Transition t o t h e 'persistent' state.Selc11al-Reddy --. ~ - -. . Hyderabad. Satyam Theatre. : Hibernate-Persistent Object Lifecycle I ... -. // modification o f t h e object w i l l automatically be saved scheduled //because the object is i n t h e 'persistent' state // (actually alters t h e initial insert statement since it hasn't been sent yet) account .blogspot.setBalance(500).getTransaction(). .

23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj.Entity. 1 @Override public String tostring() { return "Account [accountld=" t accountld t ".persistence. 13. 6. 1 --- Session m e t h o d s j I -- 10. H [be1nate-Session Methods I i I 1 . } public void setAccountld(int accountld) ( this. 7. private String name. : 31. Hyderabad. - Mr. i 5. t import javax. } public void setName(String name) { this.. private double balance. @Id @Column(name = "ACCNO") public int getAccountld() ( return accountld. ~ l n p o ijavax. 17. 16. Naresh i Technologies. @Column(name = "BALANCE") public double getBalance() { return balance. Ph: 040-23746666.pers~stence.--.SeltharReddv - - I a m going t o use the following e n t i t y t o explain t h e session methods. 25.Table. 18. ! ..blogspot.persistence. 9ackage corn. 15.hibernate. Opp.accountld = accountld.com Page 40 1 1: - .Column. 1. 12. 1 i1 -. I public void setBalance(double balance) ( this.ld. 27. Satyam Theatre.-. @Entity @Table(name= "ACCOUNT") p~tblicclass Account ( private int accountld. 19. name=" t name t ".sekharit. 26. import javax. 2. 9. 14.name = name. 1 . .persistence. 4. 20. 11. import javax.- . ! 1 1 I1 i ' . 8. 28. @Column(name= "NAME") public String getName() ( return name. 3. Ameerpet. balance=" t balance t "I".balance = balance.entity.

load(Class. 1. So we no need t o write try-catch block t o handle this exception. Naresh i Technologies.get() and session. I 4) Use this method if i t is sure that the objects exist. 2) It is lazy loading. if object is not found on cache as well as on database. i I 5) It is just like EntityManager. I 5 1 I ' 1 ) It is just like EntityManager. .get() returns a fully initialized instance.g. I 3) As Session. load() or getReference() can be used t o have better performance. session.(3bjectNotFounilExcepti~ri': - > As we can see the ObjectNotFoundException hierarchy. Means when we call session.hibernate. i 3) As Session.blogspot.0bjectNotFoundException' if object is not found in cache as well as on database. Satyam Theatre. Both looked quite similar t o each other but there are many differences between load and get method which can affect performance of our application.load(Class.23734842 An IS0 9001 : 2000 Certified Company Page 41 2 http://javabynataraj.4. When we try t o access the non-identifier properties from the proxy object.load()return proxy instance.getReference0 method of . Opp. identifier) method it will hit the database immediately and i load entity object and return entity object.)What are the differences between load() and get() methods? Hibernate Session provides two method t o access object e. I .load().find() method of JPA NOTE: If working with detached objects is not needed. Ph: 040-23746666. Hyderabad. :Type hierarchy of 'org. so it is not fully available in any future detached state.hibernate. so i t is fully available in any future detached state.lPA 1) It will return 'null'value. I 2) It is early loading.. Ameerpet. 4) Use this method if i t is not s u e that the objects exist. . it will 1 return proxy object. at that time it will hit i the database and load the entity object.com . rrieans when we call session.. - /. identifier) method i t will not return entity object. we can say this is un-checked exception.) Throws "org.

And if observe on the variables window.println(account. 58.println(account.9001). And if observe on the variables window.23734842 -- -- An IS0 9 0 0 1 : 2000 Certified Company -- http://javabynataraj. 59. I NOTE: Session. session. //account object initialized with database data // System. session.getSession(). //After this line yo" can find select query on the console. Session session = SessionUtil. ..out.getSession().com Page42 3 I J- . try { 54.beginTransaction0. 57. After this line executed. w h i c h . 52. k Now observe the console.println(account. Opp.9001). After this line executed.blogspot. System. Account account = (Account) session. w i t h the proxied instance in I -- rnailaged state NOTE: load() method exists prior t o get() method which is added o n user request. Account account = (Account) session.out. Ameerpet... i f object present w e have t o implement some logic. Hyderabad.getName()).class.load(Account. 4.getName{)). get(): if the object is not there.load() or EntityManager. // no problem!!! W h e n t o use Session ~ e t and 0 l o a d 0 i n Hibernate I 1. 55. Then w e can implement above requirement as follows if(object == null){ I //some code IL Naresh i Technologies. account object not initialized. 60. 50. //This would fail!!! publicvoid callGet() { Session session = SessionUtil.p'oint. 62. 61. 56. 53. And now account object is initialized with database data.getName()).beginTransaction(). it returns null. } catch (ObjectNotFoundException e) { j _ i iI i 1 1 // System..class. / / w e can find select statement.getReference() should be used if a fully initialized instance is not needed.out.gct(Account.H i bei-nate-Session Methods -. saves a database roundtrip if nothing other than creation of an association is done.'. Now observe the console. / / ~ this t line put Break. / / w e can't find any select statement.) HOW to call g e t and load methods ? : 1 1 ' ! 1 I 1 ( . Satyam Theatre.point . // At this line put ~ r e a. public void callload(){ 51. // Now account is just a proxy object. if not w e need t o implement some other logic. Ph: 040-23746666.

50 whatever modifications done t o the object. ~ ~ c. 2. x ) * cr.. iil.. . you'd have a LazylnitializationException in your JSP.23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj.. If you we want t o use the JavaBean that you are retrieving from the database after the database transaction has been conimitted.:"c~et(Gring tntit.:~C!C~E Icckka.Sesric1. When there i s no record in t h e database.t.lc i::II Lcckl.- . t> c ~ j ! : .5 clarz. getQClasl: clazz. and you want t o pass that instance t o a Java Server Page for display purposes.tion: Icck0pticn.1 7 <::a .ializ3t:le il:l. that tends t o be most of the time. Lccl. .it~g~ t ~ t i t : . For example. Ph: 040-23746666. get(Clar. 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.~p ~ ..ior. x ) Overloaded get() met hods (Hibernate 4 . .j t .! : l ! . otherwise.. Serislisable id..:I'~.:i gtt(Stl.: .. if you load a User instance in a Servlet. ' l ' l a r rSel. Lccki?l.l : Ot:~!cct . Ameerpet. 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.islizatl:lciclj : c. S~l. :. Opp. . 3.le) : Object . S ~ 1 . you'll want to use the get method.islizablc ~~... .:icct ).. So we can't implement this requirerne~itusing load() For the above requirement we go for get() method.I21-17~ 5~1-isliz~1:.Sel<hai-Reddy ! I //some other code I load(): if the object is not there it throws an exception.:Options lc1ck0l:tjct1:> : Object Q) When update() method has t o call ? Transient state? Transient state means the object is not associated with session and not presented in database..-. . If the object is in the persistent state then the object is said t o be synchronized with database. : gct(Clas5 clarz. . .com Page 443 . and quite frankly.- p~ ~ Hibernate-Session Methods Mi-. Hyderabad.:l. you'd need to use the get method. C. . Overloaded load0 methods (Hibernate 4 . get() method could suffer performance penalty if only identifier method like getld() is accessed.e1.lstj~~.. 1 3 l i r a bid: l t LI=CI..blogspot. c.l.*:.-icct . c~ct(5tringentit:. - Naresh i Technologies.~~lccle Icckhlocle) : Ot. Satyam Theatre.

/ / I F RECORD EXIST If( obj != null){ // UPDATE THE RECORD updatejobj). 9.. 2.getTransaction().setAccountld(1001). . 23734842 IS0 9 0 0 1 : 2000 Certified Company http://javabynataraj. 6. Arneerpet.setName("sekhar"). 11. public void saveOrUpdate(0biect object) throws HibernateException. //SELECT THE RECORD Object obj = session.com Page44 5 l1 - . If t h e record is n o t there i n the database ~t wrll try t o insert the record.. Satyam Theatre. 13.00). Hyderabad. Naresh i Technologies. Hibernate-Session Methods -- - -. //Now saveorupdate() internally calls save().get(object). -- Mr. 3. 3. -~ ~.saveOrUpdate(account).begin(). :: 10.Sel<harReddv / those changes will be updated i n the database and vice versa. account. 4. 7.': Ex: Table ACCOUNT Application code: 1.~. . I 1.blogspot. j t: 1. update the record. Ph: 040-23746666. 12. 8. 12. Account account = new Account(). / 13. ! 11. . session. 5. session. 5. Opp... account. 1 4..getTransaction(). . 1 i 2. 1 Pseudo code o f saveorupdate(): class Sessionlmpl implements Session{ public void saveOrUpdate(0bject object){ 1. .setBalance(6800. So we no need t o call update() method when object is i n I persistent state. -- . 10. Session session = SessionUtil. ) else{ // IF RECORD NOT EXIST // INSERT THE RECORD save(obj). If the record is there i n the database i t will t r y t o . 1 IS i I I I \ I Detached state means the object d o any n~odificationst o the object w e should call update() method. session.getSession(). account. Because in thls state the object is not synchron~zed I 1 I ' I >. because record with 9001 i d is not available i n the database.: -- . Detached state? I ' not assocrated with session b u t presented In t h e database In this state if we w a n t t o w i t h database.commit().

6.p. Once t h e transaction is completed we need t o close the session..cla~~. .setAccountld(1001). 8.get(Account.. w ACCOUNT NAME !=NO I1 1001 BAL 6800 1 Application code: 1. I ! 12. Account account2 = (A~~ount)session. Ph: 040-23746666. When we close t h e session all the associated objects I I w i t h the session will be de-associated f r o m session and associated JDBC connection also closed.get(Account.getTransaction(). 5.getTransa~tion(/begin().saveOrUpdate(accour~t). . account.SeltharRecidy . Account accountl = (Account)session. account.getSession().-p---p-pp-.23734842 An IS0 9 0 0 1 : 2000 Certified Company -- A http://javabynataraj.setName("new sekhar"). . Because the record with 9001 id i s already exists i n the database.blogspot.-. accountl. 8. Table: Mr. ' 11. session. account2. session. 1 Table: ACCOUNT 1002 1 Application code: 1 1.-- Hibernate-Session Methods ... 7. 6. 10. 1 I Naresh i Technologies. i 4. session.commit(). session. 5.. // Now accountl and account2 objects are in persistent state.getTransaction(). Hyderabad. - 1 I 1 1 Kesavareddy 9500 3. It is not strictly necessary to . 3. 9.- . 7. Session session = SessionUtil.class.setNarne("selthar Reddy"). //Now saveorupdate() internally class update(). Ameerpet.I i I ! I ACCOUNT Table: I ACCNO / 1 1001 I rekhar Reddy 1 8200 NAME I BALANCE ) 1 I public Connection close0 throws HibernateException.00). Satyam Theatre. I account.1001).getSession().~ . 2. I 1 Account account = new Account(). 4. Session session = SessionUtil. .setBala1ice(8200. 9. -.~etName("newkesavareddy").com Page 45 G . 13. 10..begin(). 2 . I This method is used t o de-associate all t h e objects f r o m session. -. - . Opp. i 'I public void clear().1002~. close the session but you must at least disconnect() it. i i .

i.getTransaction(). session. session.. Account account1 = (Account)session.setName("new sekhar").getTransaction().blogspot. .commit(). 12. //Now account1 and account2 objects are in detached state. 13. I ! ~.clear().23734842 A n IS0 9 0 0 1 : 2000 Certified Company http://javabynataraj. 1 1.get(Account. A f t e r execution: ACCOUNT ACCNO BALANCE sekhar kesavareddy I i i n the above example. session.1002).getSession().conimit(). Session session = Sess~onUtil. r 1.1002). accountl.class.begin(). 13. 12. 11. // Now accountl and account2 objects are in persistent state. Satyam Theatre.1001).get(Account. 9.I - I 1 . ---- -. Ameerpet.getTransaction(). account2. 4.get(Account. 3. 14.class./ I 1 I ! / p p . 6. 10. Mr. Account account2 = ~Account)session.getSession(). Table: ACCOUNT ACCNO BALANCE I 1001 1 sekhar 1002 I kesavareddy I 9500 I 1 I Application code: 1. a c c o u n t l and account2 objects will be de-associated 1 ) f r o m t h e session object. 2. Opp. Hyderabad.class. . So even w e are committing the transaction the modified I I i values o f account1 and account2 are n o t updated i n the database. //Now accountl and account2 objects are in detached state. I / iI public void evict(0biect object) throws HibernateException: This method is used de-associates t h e specified object f r o m session. session. session. Naresh i Technologies. 7. 5. Session session = SessionUtil.~ ~~ ~ Hibernate-Session Methods -. 11. .get(Account.setName("new kesavareddy").com Page461 .class. 4. Account accountl = (Account)session.SekharReddy --:: ! -. when w e call session.e. account1 and account2 objects are moved f r o m persistent state t o detached state. 8. Account account2 = (Account)session.clear().1001). 14. Ph: 040-23746666.clear() method. 9 N o w a c c o u n t l and account2 are in non-transactional state. 5.

SeltharRedcly -- .1001). .out. 4.com . 14. 15.evict(account1).out. I I 7. I I I ' 5.get(Account.println("account is not associated with session").19. acco~1nt2.getTransaction(). 14. 1 1 1 System. Session session = SessionUtil. 2. accountl. 10. if(session. 12. 18. - 1 I ACCNO I NAME 1002 i - ACCOUNT ! public boolean contains(0bject obiect).out. 11.contains(account)){ \ .H ibei-i~ate-SessionMethods - I 1 -- - 6. Ph: 040-23746666. System. I 9 After calling transaction.class.getSession().clear(). 9. // Now accountl in detached state and account2 in persistent state. session. Because i t is in persistent state.println("After calling clear() method").evict(account1) a c c o u n t l object will be de-associated f r o m sesslon I .~ut. session. I I Application code: I I I 1. . 17. 8. 6. I It is used t o check whether the object is associated with session or not.blogspot. 13. Hyderabad.println("account Is associated with session").contains(account)){ Systeni.println("account i s not associated with session").commit().setName("new sekhar"). 9. } System. i After Execution: I ' Mr. if(session. . u r i 10. Satyam Theatre.println("account Is associated with session"). object. only account2 object will be updated.setName{"1iew kesavareddy").out. } else{ session.commit(). I 1 BALANCE I 1 1 8400 1001 I sekhar 1 n e w kesavareddy 9500 ~ 1 'i evict() is used t o de-associate specified object f r o m the session object. 16. 1 7. } else{ System. 'i In the above example when w e call session. __I. Opp.println(~'After calling get() method1').out. 1 j 12.23734842 An IS0 9 0 0 1 : 2000 Certified Company > Page 847 http://javabynataraj. Account account = (Account)session. 13. Ameerpet. 3. Naresh i Technologies. // Now accountl and account2 objects are in persistent state. System. } I i I 1 public boolean isConnected(L To check weather there is a connection is associated w i t h t h e session or not. 8. 11.

4. 9. - - .flush() because when we call transaction. session..out.println("not connected").out.-p---p--. 7.flush(). ! - i --. a .begin().. I Account account = (Account)session. if(session.1001). .close(). System.- - ~ a r e i Technologies.setBalance(9500). System.getTransact~on(). 11. If it f ~ n d s I I different ~twill update object data into database. Ameerpet. }else{ 11. When you need t o upload a large number of records into our database by using hibernate we are using the below code. 6.getSession(). - .commit() is called it will also check object data and corresponding record data. 6.~ . 8. Batch processing is the process of read~ngdata from a persistent store. . This method is used to synchronize session data with database.out. 10. if(session..isConnected()){ 9. 9 We are using flush() and clear() methods of the Session API for the batch insert process. Hibernate-Session Methods .~~- Mr. 1 ( 4.~. Satyam Theatre. I - Session session = Sess~onUt~l..getTransaction(). account. when computer resources are less busy.out.----.flush().commit().Sel<hai-Reddy -. 3. 9 So after transaction. 5. lo. session. 1 Application code: 1.getSession(). Batch Processing 9 The execution of series of programs is called batch processing. 2. I i I 8.out.commit(). } public void flush() thicws HibernateException.println("connected"). If i t finds difference. Page48 9 http://javabynataraj. 7.I [ I 9 When transaction."). System. session. I 3. 12.println("not connected"). 23734842 An IS0 9001 : 2000 Certified C o m ~ a n v ---. Hyderabad. we should not call sessioll.isConnected()){ System.p. doing something with the data.~etName(~'new sekhar").- ~ 1.blogspot.com .. ? session. 5. I I 3 In the above example when we call session. it will execute update query t o update object data into the database record.. Session session = SessionUtil. Hibernate checks or compares account object data and corresponding record database.cornrnit() I session is in sync w ~ t hdatabase I .println("connected").. Ph: 040-23746666.get(Account.Point and observe the conscle. account.. and then storing the processed data in the persistent store I ~ 1I i -I 1 9 Usually we run Batch process. .pr~ntln("Breank. s Opp. 2..class. }else{ System. .

. 3.beginTransaction().23734842 IS0 9001 : 2000 Certified C o m. Session session = SessionFactory. Satyam Theatre. i L IVaresh i Technologies. session. session. .getSession().Mr.flush(). This shows the hibernate container t h a t every X rows t o be inserted as batch.getTransaction(). / - 1 I 1 I I I I .-- Hi bel-nate-Session Methods _ _ I Eg: 1 Session session = SessionUtil. session. begin(). This method is used t o synchronize the database data with session data. Transaction tx = session. Ernployee employee = new Employee(.commit(). if( i % 50 == 0 ) { // Same as t h e JDBC batch size 8.. } 12.. Ph: 040-23746666. v An -- http://javabynataraj. 11. tx.getSession(). 7.clear(). To understand the importance o f refresh() I m e t h o d observe the following scenarios.close().1 13. session. 6. i++ ) { 5.Batch processing helps t o resolve the problem o f OutOfMemoryException. session. i<1000GO.openSess~on().beginTransaction(). 1 The prime step for using the batch processing feature is t o set hibernate.blogspot. 15. Session session = SessionUtil.com 49 Page 10 . //flush a batch o f inserts and release memory: . Casel: w i t h single session. Transaction tx = sess~on. Arneerpet. Hyderabad.save(employee).jdbc. I I II public void flush() throws HibernateException.). Advantage:.batch-size i as batch size t o a number either at 20 or 50 depending on object size. ~ a n.SeltharReddy .i I 9. Opp.).save(employee). I Eg: - I. session. ic100000. 14. 2..2. for ( int i=O.. single t i m e calling get() method: I - Table: ACCOUNT ACCNO I I BALANCE sekhar I 1 Application code: 1. 10. i++ ) { Enlployee employee = new Employee(. 4 for ( int i=O. .

").getName()).. session.0 g database . 8. System. - -.class. 6. 2.. ~ a n.out. 3. 5. Ameerpet.out.println("Name : " + account..23734842 An IS0 9001 : 2000 Certified C o m. 14.com Page 50 11 .pr~ntln("Name: " + account.0 1 Explanation: > When w e call the get() o n session object. 15.out.blogspot. And finally that entity object will be cached o n the session object.class. I I CaseZ: w i t h single session. System. Break .println("Balance : " + account. session. Name : sekhar Balance : 8400. System. After ~ ~ p d a t i nthe Name : sekhar Balance : 8400."). L Account account = (Account) session. session.println("After updating the d a t ~ b a s e..get(Account. go t o database and modify the data ACCOUIVT / ACCNO I 1 1001 I ( NAME 1 sekhar new 1 BALANCE 9500 1 7 11. v -- http://javabynataraj. Account account = (Account) session..getBalance()). // 10.getNanie()). Ph: 040-23746666.println("Balance : " + account.getSession().. Opp.out.println("Before updating the database. Naresh i Technologies.point. Hyderabad. 5. System.- . 16. 13.begin().~elthar~edciy -\ 3. Just it always shows session cached data.getTransaction().close(). it will h ~the t database and get the data from the database and creates - entity object and assign the retrieved data t o entity object. I .").getBalance()).. multiple times calling get() method: Table: ACCOUNT I ACCNO 1 NAME I I I 1001 1 BALANCE I sekhar 8400 Application code: 1. Session session = SessionUtil.getTransaction(). I When w e update the data o n the database i t will not get the updated data. 7. 12.out. 1 Output: Before updaticg the database . ..out. 4. 1001).println("Before updating the database.commit(). 4. 9. System.. 1001)..out. Hibernate-session Methods - - - - ~i-. System. Satyam Theatre. 17. System.get(Account.

Systern. I 17. Hyderabad..out.. 9.point .c~ass.. 2.Hibernate-Session Methods- -- MI-.getName()). Case 3: creating multiple sessions. it will not hit the database.1001).getSession(). Account account = (Account) sessionl. 6.") . Satyam Theatre.println("Name : " + account.out. Table: ACCOUNT 1 ACCNO 1 NAME ) I 1001 I sekhar I 1 BALANCE 1 1 8400 I 1I Application code: 1.getTransaction().0 After updating the database . 18.getSession().out.println("Balance : " + account getBalance0). 13. it will check whether the object is available in session or not.getName()). - I I -1 I / Output: Before updating the database .println("Balance : " + account. That's why even we call get() method on session object 2ndtime.23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. Name : sekhar Balance : 8400.class. Ameerpet. 10. If the object is available in session..0 Explanation: > When we call the get() on session object(second time). Session session2 = SessionUtil.out.--- l 8. 4.. 5. 3.SeltharReddy - -- . 14. Opp. 1 new 9500 account = (Account) session.out.cornmit(). session. Ph: 040-23746666.. 7. it will not hit the database. session.. // Break."). Session session1 = SessionUtil.. instead it displayed previous data only. Name : sekhar Balance : 8400.println("Before updating the database... 12. System. Systern. I 15..get(Account.out.blogspot.println("Name : " + account. System. 16. > In above example with Accno 1001 already account object i s already available i n session object.println("After updating the database .getBalance()). 1001). Naresh i Technologies.get(Account.close(). System. go t o database and m o d ~ f ythe data ACCOUNT m] 1 BALANCE 1 I NAME /-tsekhar / ' 11.com 51 . Systcm. That's why it didn't display the updated record data of database.

- ~ .getName()). System. To solve the above problem we can use refresh() method... 1001). System. ' : I i Output: Before updating the database . Ameerpet. Satyam Theatre. 8.getBalance()). ' 1 I I I I j / . i i I i In the above example.out.. 1 ACCNO ) I 1001 / sekhar I NAME / BALANCE I 1 1 8400 I 1 I :: Session session = SessionUtil.. IVame : sekhar Balance : 8400.getSession().out.Sel<hal-Reddv 1 8. go t o database and modify the data ACCOUNT ACCNO NAME BALANCE 1 Naresh i Technologies..0 Explanation: ! r I method on session2..out. -. System. ACCOUNT 1 1001 sekhar new 1 9500 I I I 10..out. // Break. Hyderabad. I . System. 23734842 II An I S 0 9001 : 2000 Certified C o m. v _ - http://javabynataraj.println("Name : " + account. ~- .println("After updating the database . Ph: 040-23746666. Mr.out. . 1 Case4: using refresh() ACCOUNT Table: 1 I I Application code: / 1. That's why when we call get() I 1 But here every time we are creating new session object t o get the updated Record.com Page 52 13 I I I.0 After updating the database .getBalance()).p oint .-- --.get(Account.out.println("Balance : " + account.get(Account. - -- Hibernate-Session Methods . Account account = (Account) session... --- .. 1001). session2 object doesn't have any associated objects.println("Balance : " + account.-.. ..cIass.").. I // Break ... System.. I 12. 6. System.. 5. account = (Account) session2. ~ a n. 13..point . ..println("Name : " + account. go t o database and modify the data 9.println("Before updating the database.blogspot. Opp."). I 11.getName()). i t hit the database and executes the select query and retrieve the record and display the i updated record of database..class. Name : jekhar new Balance : 9500.~ I - -. 4.

Satyam Theatre.println("Balance : " + account getBalance0). 8.commit(). 12. If it finds any 1 difference it will again execute select query and update the object data.- I - Page 14 http://javabynataraj. Mr-SekharReddy ' -2 1 9500 I 9. 12.NonUnique0bjectException: a different object with the same identifier value was already I associated with the session: [com.refresh(account). 1001). 3. Consider the following example. 2.com 53 .out.blogspot.-. 7. 11. - - i public Obiect mergejobiect obiect) throws HibernateException.- I I Explanation: > I In the above example when we call refresh().--.class.Account#lOOl] Naresh i Technologies.get(Account.println("After updating the database . 11. session. Ameerpet.getTransaction~).sekharit..1 1 Output: org.setBalance(6500). Account accountl=(Account)session. 9. Hyderabad. Name : sekhar Balance : 8400. Name : sekhar new Balance : 9500.23734842 An IS0 9001 : 2000 Certified Company ---.println("Name : " + account getName()).0 ' . . -.entity. Account account2= new Account(). System. session. 4. account2. 6.out. session. session.begin(). account2. Ph: 040-23745666. ! I -.Hibernate-Session Methods ---- v 1 sekhar new I Output: I Before updating the database . System. 10. Table: ACCOUNT ACCNO NAME BALANCE 1001 sekhar 8400 Application Code: 1. account2.").out.... System. 1 I ' .update(account2)... Hibernate compares database data and object data.hibernate. Opp.getTransaction().. 5.setName("cherry"). lo...0 After updating the database ..setAccountld(1001).hibernate.

we won't get exception.. 5.blogspot.----.#:I ._ .:I . 2. merge() method behave differently in different scenarios. account. 6. I II > 1 > I I In the above example. . account. 4.I :I -1 111 111 -1 .-I' .merge(account).~rlt2<-l IIIUI 2 -- '------ - . > i In the above example. .00).Sel<harRedciy ---- ----. 8.- -_--/- -- - Mi-.311: : I CI I-A ---- I .- < ~~ -'-. 23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. . Ph: 040-23746666. merge the data.-- - - ~. update. i - I 1 Case 1: merge() method insert the data j Table: I ACCOUNT ! I BALANCE ! I sekhar Application Code: 1. Satyam Theatre.com Page54 15 1 .. session.:y <.begin(). It is I the problem.- r~t .~t1:: . Opp.. p . Hyderabad.I ---- -- 13i:~ilL../-- ( I . If we use merge() method instead of update() method. - - _-------/- I: '-. account. session. --. p Hibernate-Session Methods ''------ :ze :% 15:1 1 1 1 rl . 1 i I 1 ! To understand more clear about merge() method consider the following cases. by calling get() method account1 object with identifier '1001' will be there in session. merge() method can insert. -- -. And by calling update() method account2 object with identifier '1001' is also trying t o come into session object. Session session = SessionUtil. Account account = new Account(). 1 I After execution: ACCOUNT 1 ACCNO I NAME ( 1001 1002 I 1 BALANCE 1 1 Sekhar 1 8400 cherry 4500 1 1 1 / 1 I Naresh i Technologies. 10. Ameerpet. Just account2 object data will be updated into database. .getTransaction().setAccountld(1002).setBalance(4500.->' --.getSession().-.setName("cherry"). I I I I i 9 We can't place two different objects(of same type) with the same identifier in the sesslon object. 7 . - -~p . To avoid this we will go for merge(). 9. p . .--- ---c- --/--- 3:e :z:5..I13 i-1 -1-4 111114ate 1: 11 \ .. .

.. Session session = SessionUtil. Account accountl=(Account)session..- - - Hibernate-Session Methods ....commit(). account.. Naresh i Technologies..getTransaction().23734842 9001 : 2000 Certified Company An IS0.merge(account)..setName("yeIlareddy").getTransact~on(). 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.getTransaction(). session. 2. cherry. 1 yellareddy. . it will insert Account(1002. . .blogspot. Satyam Theatre.... I Case 2: merge() method update the data Table: ACCOUNT IVAM E ACCNO Sekhar 1002 cherry 4500 Application Code: 1.. I As we don't have a record in ACCOUNT table with ACCNO#1002. .. session.. 7. session.. 5600.. 9. 2.getSession(). 12...00). . 1 After executiori: ACCOUNT I ACCIVO NAME I BALANCE ( Sekhar yellareddy P 1 - 5600 i In the above example. i t will try t o update with latest Account(1002. .. 11.. 4.00) object into database.. when we call merge() method.- - --- . . account.. 8.. .setBalance(5600.getSession().close().. 1001).class..setAccountld(1002).. . . 4500.-. Hyderabad.. session. Session session = SessionUtil. . . first i t will try t o load Account object with identifier 1002. account.. .00j object into database. 6. first i t will try to load Account object with identifier 1002.. http://javabynataraj. - -- - Mr.. 13.. 3. 3..... 5. Ameerpet.- -. ..get(Account.com 55 page-%- . Ph: 040-23746666.. Opp...begin(). session.. As we have a record in ACCOUNT table with ACCNO#1002. when we call merge() method.begin()..---..Sel<harRec!dy 3 In the above example. . Account account = new Account(). . 4... 10. .

. -. and if i t is sure use update for the data persistence in hibernate.. Ameerpet. . 1 After execution: i . Copy the state o f accoun2#1001 object state into accountl#1001 object. So merge() method now. accountl#1001 object is already associated with session.class. I public Serialiiable getldentifieriobiect object) throws HibernateException. merge (): Irrespective of the state o f a session. L I 11 1 i . 12.com Page 56 17- . '1 System. . 7.blogspot. h accountl is in Persistent state. weather there i i any object associated with . 1 I <- 1 I- . Opp. I ! To know the object identifier value at the runtime. 1 Transaction methods: I Naresh i Technologies. After llth line also. ~ /--. > In the above example.SekharReddy Hibernate-Session Methods - . Before llt line. 14.merge(account2]. 9.out. 1 i - . I i I .23734842 An I S 0 9001 : 2000 Certified Company --- http://javabynataraj. use merge(). account2. Serializable id = session.-. Hyderabad. . As acountl#lOOl(Persistent-state) data is modified. . In the above example.. and account2 in detached state. 13. ' I . In our example. . ---.--.setAccountld(1001). ACCOUNT ACCNO BALANCE yellareddy I I / .close(). Account account2= new Account(). ! i Q) What is the difference between merge and update? i update () : When the session does not contain an persistent instance with the same identifier. Ph: 040-23746666. when we call merge() method it will check.--~-- Mr. so i t will hit the update query. I j 11. I 10.setBalance(6500). account1 is in Persistent I j 3 When the transaction is committed. account2. account2. Satyam Theatre.. . session. session. > I .-. and account2 in detached state.getldentifier (account). I 5.println("Identifier of Account is : "+ id).setNarne("kesavareddy").- : .1001). t o update session data with database.get(Account.commit(). session. state. we need t o call getldentifierfobject object) I 1 Application code: II Account account = (Account)session. 6.~.getTransaction(). . - the session with same identifier(1001). i f there is a need t o save the modifications at any given time.__ . 8..

0VERWRITE : this mode reads the processing request and affect the result in database. then i e can f o i persist() method. 1 1. Ph: 040-23746666.getSession(). then we can go for save() method.lGN0RE : this mode ignores the processed request. .-. Session session = SessionUtil. I beginTransaction0 return different transaction objects. For each and every request transaction object creates a~lcl begins new transaction context. P ReplicationMode.com 57 Page 1g .-- http://javabynataraj.23734842 An IS0 9001 : 2000 Certified Company -. Transaction transaction = session. P ReplicationMode. Hyderabad.- -- - -. I > i - which is generated by generator class. but save(object) returns identifier and persist(object) doesn't return any value. session. Transaction transaction = session.' . When we are using generator classes t o generate the identifier. ~ e a n ist doesn't affect the result in r ReplicationMode.blogspot.beginTransaction(). After committing the transaction the results are stored in database.- - -pp. Ameerpet.EXCEPTl0N : this mode reads the processing request and affect the result the database.Sel<harRedcly We can apply Transaction management by using transaction object II We can get the Transaction object in 2 ways.LATEST-VERSION : this mode reads the processing request and affect the result in database. Satyam Theatre.getTransaction(). 1 I I I Application Code: 1. M e t hod Signatures: public void replicate(0bject object. P ReplicationMode. ReplicationMode replicationMode) throws HibernateException. Opp. 3 This method is same as save().: Naresh i Technologies. I getTransaction0 return same transaction object for every request. datadase. We need t o call begin() on transaction objecl l o begin the transaction public void persist(0bject object) throws HibernateException. begin().- I -. At that time if we want t o know identifier value 3 When we don't want t o know generated identifier. ReplicationMode has attributes described below.--p-- Hi bernate-Sessio~~ Methods - Mr.getTransaction(). This method is used t o move the object from detached state t o persistent state.

x version Ih . LockMode IockMode) throws HibernateException. if that is supported.WRITE: Is obtained automatically when Hibernate has written t o a row in the current Transaction.READ : Bypass both levels of cache.println("After replicate() method"). I NOTE: this method got deprecated in Hibernate 4.out.println("associated").contains(account)) { Systeni. System. } else { System. 1 I I work is completed. I I P LockMode.println("After evict() method").com pa e 58 1 F ' . i I If w e are updating some group of tables no other person is allowed t o update the records on the same table until our II transaction.out.println("associated").out. Ameerpet.class. } session. if (session.. Hyderabad. System.contains(account)){ System. and perform a version check and obtain a database-level I I I I pessimistic loc upgrade lock.NONE : Don't go t o the database unless the object isn't in either cache. if (session.LATEST-VERSIOIV).get(Account.evict(account). 1 session. thus throwing a locking exception can't be obtained. and perform a version check t o verify the object in memory is ! the same version as that currently exits in the databse. - Hibernate-Session Methods -.out.out.out. Satyam Theatre. . I I 1 This is an internal mode and can't bespecified explicitly.println("After get() method"). } else { System. but use a SELECT .println("not-associated"). Ph: 040-23746666.replicate(account. 1 P LockMode.-. { i f (~ession. FOR UPDATE NOWAIT on Oracle. Opp. This disables waiting for concurrent lock releases. So using lock(). I Naresh i Technologies.contains(account)) System.UPGRADE-NOWAIT: same as UPGRADE . I I - 9 LockMode.println("not-associated").out..UPGRADE: Bypass both levels of cache.--.out.out.println("not-associated").println("associated"). 1 public void IockiObiect obiect. i f we lock the record i t doesn't allow updating from different users till we commit the Hibernate defines Several lock modes P LockMode.. Systern.23734842 i An IS0 9001 : 2000 Certified Company I - http://javabynataraj.blogspot. - MrSekharReddv --' Account account = (Account) session. I 3 LockMode. 1 else i System. 1001). ReplicationMode..

SeltharReddy Q.0 3 mysql command line client Give password 4.) H o w t o work with MYSQL database? ! I install the MYSQL database. Hyderabad....~ ~ . Ameerpet.. and give use mydb command. In the MYSQL prompt give the following comr-riands o Create database mydb o Use mydb 6 Now perform database operations normally._ .---.blogspot. A ~ ~ .. ~ .. 23734842 An I S 0 9001 : 2000 Certified Company - http://javabynataraj. Satyam Theatre.---.2) - i 1 I I IVaresh i Technologies.)How t o connect t o m u l t i p l e Databases using Single Configuration File in Hibernate? I OracleDataBase Table: I SQL> desc account.. Ph: 040-23746666..-...-... i Name Null? 1 I TYpe _ _ _ _ _ -_ ..com Page59 ._ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ I ._ .--._ . (don't give create database mydb) I I I I i ! ! I ! i I ' I Q..- 1 ACNO IVUMBER(5) BAL NUMBER(8.. ~ ~ ~ Hibernate-Multi Database Communication 1 By Mr.. C? Select All Programs 3 MYSQL 3 MYSQL 5. ...--. C When you open mysql command line client again just give password. Opp.

prlvate Strlng name. publlc void seiAccno (lnt accIlo) ( 13. 1 10. { I Naresh i Technologies. +-.-. I 19. 24. t. thls.blogspot. 8.com 1 I- ..'i . package coin. public void setBalance(doub1e balance) 29.VO. SeltharReddy. public class Account ( 4.name = name..+ ---<- I Field I Type 1 acno i 1 I name 1 int(5) ( Null I Key ( Default 1 YES 1 I char(l5) j YES 1 I NULL I I I 1 NULL Extra ( ( 1 Account. I I I I . * I j / 1 1 3 .- ~~~ ~ ~ ~. public double getBalance ( ) [ 25. ~ By Mr. 7.-----. I 27. ~ ~ Hibel-nate-Multi Database Commu~~ication --- . 2.. -\ MySQLDat B e Table --+ +----.-+----. . 1 2 . prlvate.accno = accno. 22. t 5. I 30.23734842 An I S 0 9001 : 2000 Certified Company Page602 http://javabynataraj.. return accno.-+----------. I I 1 .~ n accno. ~ r n e e r ~ eHyderabad.neo. return name. 28. 31..iava 1. 6. 1 15. 16. ll.hibernate . this. 20. privatedoublebalance. public Strrng getName() ( 17. 18. I 23. return balance.a. Ph: 040-23746666.. public vold setName (String name) [ 21. this. publlc int getAccno0 { 9. Satyam Theatre. 26. Opp.+. 14.balance = balance.

Opp.1 .DriverManager.. System. 4. Configuration configuration = new Configuration(). Hyderabad.neo.. package com. 16. sql . . 7.buildSessionFactory(j. System. System. System. - ~ .~ . System.get(Account.openSession(ConnectionUtil. System.. ~~ Hibernate-Multi Database Communication --..mysql.. .out... System. 8.ut11... 7. lmport java.println("0racle Account table details .getName()). .out. System. public class ConnectionUtil { static { 9.println("Accno : "+oracleAccount.Session. import com.-- By Mr.getBalance()) . 23. 29..hibernate.forName("oracle. 31. 33. 15. 4 ... Class. lrilport org.out.neo.vo.println("Accno : " .openSession(ConnectionUtil. package com.jdbc.SQLException.blogspot.. 32. 2..Account.. .println("Ba1ance : "+oracleAccount. configuration. 28. Ph: 040-23746666.iava 1. 21. 24.hibernate.getName ( ) ) . 19.sql..println("Mysq1 Account table details .. 6.getOracleConnecti~n()). Class. 20. 9.getAccno()). factory.driver.. Satyam Theatre. . //Mysql 26...OracleDriver~')..hibernate.dao. SekharReddy 7I ~ 1. 8. 30. ) 36. public static void main(String[] args) { 12. I 1-. e.. 1 34. SessionFactcry factory = configuration. " ) .~.get(Account. " ) .~.. 25. Sesslon oracleSession = 18..jdbc. .. cfg . 1001). 14. try { 10.println ("Name : "+mysqlAccount..configure("com/neo/hibernate/config/hibernate..getMysqlConnection()) . f 6..out.class.Connection.xml"). g e t A c c n o ( )) . .out.. SessionFactory..cfg. import org.util. 13.sql.out..class.neo.. factory.Driver"). ..printStackTrace0.getBalance()).hibernate.. 12. 11. 2. 35.println("Balance : "+mysqlAccount. Account oracleAccount = (Account) oracleSession. ConnectionUtil.. 3 .hibernate..m y s q l A c c o u n t . Session mysqlSession = 27.Conn~ctionUti1.com Page61 3 i I . Account mysqlAccount= (Account)mysqlSession. C ~ n iguration. 23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. import crg.hibernate. 3. Ameerpet.out. public class PracticeDao { 11. / / Oracle 17. 22.forName("com..neo.out.. 5 . 1001). 1 15. Naresh i Technologies. 14.hibernate.println("Name : "+oracleAccount.. 1 catch (Exception e) { 13. import java. import com. 5. import java . 10.

Hyderabad.. .-~ http://javabynataraj.- ( :' ~~ ~ ~- - Hibernate-Multi Database Coi~~munication -- . "root". <property name="name"></property> 8. O / / E l l r ' "http://hibernate. <class name= "com.hbm.I public static C o n ~ e c t i o cget0racleConnection() ( Connection ~ j i 1 i i . .@ / / E N u 3..-.hibernate. 23734842 An IS0 9001 : 2000 Certified Company . ( ' 39.neL/!i1berate-mapping-3. printStackTrace ( ) . ..O.Or encoding='UTF-6'?> 2 . <hibernate-configuration> 5.0" encoding="UTF-8"3'.xmlf' /> 8. .hbrn. 1 public static Connection ge~MysqlConnection() { Connection connection = null. . - 1.. "tiger"). SekharReddy --. </hibernate-mapping> hibernate. 38. 1 40. Ph: 040-23746666. IVaresh i Technologies. Satyam Theatre. Account.cfg. . </session-factory> 9. 1 return connection. Opp. . 3=: i11~11. <property name="dialect">org. I 'I I 1 I1 37. try { connection = DriverManager. </class> 10.OracleDialect</property> 7. . } catch (SQLExcepcion e) ( e. .net/hibernate-configuration-3. . </hibernate-configuration> 1 ! ! 1 I I I I I Q. .getConnection( "jdbc:mysql://loca1host:33O6/mydb"..dtd"> 4. ) catch (SQLException e) { e .sourceforge.. 1 16.j ~ ~ i . I i 1 return connectlon.sourceforge.neo. Ameerpet. <mapping resource="com/neo/h~bernate/mapping/Account.xm! 1. .- -. <hibernate-mapping> 5. "http://hibernate. "system". . . . 4. <property name="balai?ceM column= "BAL"></property> 9. try ( connection = Driv?rManager.com 624-' Page I I I 'I .blogspot. 2. <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Conflguratlon DTD 3. <session-factory> 6. <id name="accno" column="ACNO"></id> 7.)How to connect to multiple Databases using Multiple Configuration Files in Hibernate? I .xml 1. -. <?xml version='l.dtd" > 3.. .Accountr'table= f'ACCOUNT"> 6.getConnection( "jdbc:oracle:t h i r : : Plocalhost: 1521:XEW.dialect.hiberi~ate. c?xml version="l.vo. I?-. .printStaekTrac? ( ) . < ! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3 . By Mr.O.

....+ I I acno 1 I ( name ( char(l5) I YES ( int(5) I YES I I 1 NULL ( NULL I I 1 I ( bal ' ! I 1 float 1 YES I I NULL 1 1 Account... Hyderabad.. 1 i TY 1 -------.+--------.+----.......... Opp..iava Naresh i Technologies....2) ( Field I Type I Null I Key ( Default I Extra ( +-------+---------.~ u lDatabase ti Con~munication Bv M r ....com 5Page63 .~ i b e r n a t e . Satyam Theatre....... SelcharReddv ~ r a c l e ~ a t a ~ Table: ase i 1 SQL> desc account..blogspot......----------------- ACNO NUMBER(5) NAME VARCHAR2(10) BA L NUMBER(8.+------...23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. Name Null? ...+-----. Ameerpet. Ph: 040-23746666..

- ~ Hibernate-Multi Database C. h i b e r n a t e . Account oracleAccount = (Account)oracleSession. 1 .?ccnc ( i n t ?:cn. 1001) .-1I I. ne2.out.getMysqlSession(). accno = -::I::: . System. 20. .~. System. 3. 1 i i / . 6. 5. 2 . r e t u r n name. 10. t h i s .iava 1. t h i s .neo.println("Ba1ance : "toracle~ccount. import com. [ I args) { / / Oracle Session oraclesession = SessionUtil. r e t u r n accno. Opp.hib?rnate. 4. Account mysqlAccount= (Account)mysq1Session. p u b l i c i n t gethccno ( ) i 9. 14. p u b l i c v o i d set. 16. ...getBalance()).SeltharReddy--. 1 31. 7. System. . balance = halance. 18.out. 12. package com. . 1 23. I ..getAccno ( ) ) . ~ ~ ~ ~ u i ~ i c ation -. .. 1001). 28. 18. n a m e = nasa. 20.- - ByMr.println("Name : "toracleAccount.-. p u b l i c v o i d setName ( S t r i n g n a n ~ ej { 21. : - . .neo. Hyderabad.class. 15. Naresh i Technologies. ) PracticeDao..:?) : 13. 11.SessionUti1. 1 1 1 : j i i 1 ! i i j i 1 : 1 . . 22. System. 10. . . i-c.i http://javabynataraj. 26. public static void main(String 8. p r i v a t e i n t accno.get(Account.getAccno()).out. " ) . Sessj-on..com Page646 .. Satyam Theatre.getOracleSession(). r e t u r n belance. p u b l i c S t r i n g getName() { 17. System. Ph: 040-23746666.out. p r i v a t e double b a l a n c e . . 17. ? 15. import 0rg:hibernate. 14.neo. 3 . 24. System.hibernate. 13. import com.out.blogspot.vo. 1 1 I-.println("Oracle Account table details . 30. 19.out. p u b l i c double g e t B a l a n c e 0 ( 25. 2. p u b l i c c l a s s Account { 4. 5. t h i s . 23734842 An IS0 9001 : 2000 Certified Company --- 1 -. .o ~.get(Account. Ameerpet. 16. 8.util. 12.Account.dao. 6 . " ) . privateStringnam?. package corn. 1 27.. 3 2 .hibernate. 11. public class PracticeDao { 7.c1ass. .println("Mysq1 Account table details . p m l i c void setBalance (double iialance) i 29. //Mysql Session mysqlSesslon = SessionUtil.getName()).println("Accno : "tmysqlAccount.println ("Accno : "toracleAccount. 9. ) 19.

pr~1ltln("5alance: "tmysqlAccount. ~ .hibernate.println(getMysqlSession()) . 040-23746666. 23.Accoun t" table= "ACCOUNT"> <id name="accno" column="ACNO"></id> 67. import org.0" encoding="UTF-8Ir?> 2. 24. 10. 12. 4.Balance()) .echnolog~es.. 3. import org. ~ ~ d e r a b a Ph: d .SessionFactory.!a:ne( ) ) . 1 \ I . 23734842 An I S 0 9001 : 2000 Certified Company http://javabynataraj.out. import 01-9. 30. System. private static SessionFactory mysqlFactory.hibernate.buildSessionFactory(). 17. . -- By Mr. 20. stacic ( 13.out .openSession().blogspot.prlntln("Name : "tmysqlAccount.buildSessionFactory(!. 22. 8.xml") . private static SessionFactory oraclFactory. <hibernate-mapping> <class name= "corn.sourceforge. Conca tFunction. </class> 10. 29. 1 1 1 I 7. hibernate. 19.~ 21.~ ~~ Hibernate-Multi Database Colnmunication .hibernate. 26.qer. cfg.hbm.net/hibernate-mappng-3. 1 ! Account.openSession(). ja:<en.xrnl 1. 31. package corr. ~ ~ .~.vo. mysqlFactory = new configuration() . I - 1 ~ -.neo. 27. </hibernate-mapping> 4. S-ssion. public class SessionUtil { 9.0td" > 3. i 6. 11. 2 4 .hibernate. public static Session getOracleSession() [ return oraclFactory. . <property name= "balance" column="BAL1'></propert y> 9. cfg .: "com/neo/hibernate/config/~racle. 18. 25.java 1. 2. util.. hibernate. 1 5.xml") . I - 1 16. <!DOCTYPE hibernate-rnapplng PUBLIC "-//Hibernate/Hlbernate Mapping DTD 3.Eunction . -' 1 .: 1 1 1 ' 1 1 I 23. 1 1 SessionUtil. 5. Satyam Theatre.O//ENU "http://h~bernate. I 1 I - I I I I Naresh I l. ~ ~. 1 public static Session getMysqlSession() { return mysqlFactory.cfg. Configuration. ranf igure ( I . Ameerpet.aetl.Opp..com Page65 7 I __I I .hibernate.out.neo. import org . 1 public static void main(String[] args) { System. SeltharReddy System. <?xml version="l. 28.configure( "corn/neo/hibernate/config/~nys~ql. <property narne="name"></property> 8. n r ? c l Factory = new Configuration i : .

5L?":./ / H i b e r n a t o . 1 ' : .l:~i?iiil. -. " . ' r i ~. 6. 12. Ph: 040-23746666.. i / 5.~-'<property name= "coi~nection.... <?xml version= '1.d " > t i g e r < / ~ r ~ p e r .' 8... </hibernate-configuration> . Hyderabad..0'encoding= 'UTF-8' ? > 2.hibernate.~.icat i ~ : i ' .Bv Mr..:.<. ' j ~">erg. . ~ .'.L . p ~ ~ ~ ~ ~ ~ . : ~ ~ <property !??me="connection.?z~i~ci? :r. i S i b e r n a ~ : e C3:lfiguration DTD 3 .. ..dtd"> 4.. .url">jdbc:oracle. I 7. <!DOCTYPE hibernate-configuration P U B L I C M . hbrii. <proL2. " ~ ' . i : ~ . .. ' .c o n f i g u r a .O.-.-.. i d b e . ..i . <property n-1ln~="dia1ect">crg. <property name="cor1nection. .scurceforqe..'-.. > j C .driver~classf'>oracle. url ">jdbc:mysql: //loca?i~ss::: -.~ : ~ .password">tiger</property> <property name=rfconnection. satyam Theatre. .-. ! I .- . - . 10...:thin:@localhcst:1521:XE</property> ./ F:v.. L ' I Naresh i Technologies. "http://hibernate.-.: .I.>i-:. ' .<rill" / > </session-factor!:. . .i~>ii[~~-~~~</prcpert)/> <property !?are="zci~~~eccisn... .dialect. <property name= "con~~ection . ..c'river~class">com . C .</property> .l-liberllate. <session-fact~ory.>. Opp. ?!hi!. ... . <hibernate-ccnfiguration> 5..: n ~ r ~ .blogspot. D~:I.. 14.Stem. <hiberna~-3--...driver. . 23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. <prcpert.jdbc. ~ ~ ~ di315~.fiauratio~n> - ~ oracle. 9.- . . 13. lqhttp: //hiberliate.Orac?e9Cialect</property> 7.... Ameerpet.xml " / > 14. SeltharReddv Hibernate-Multi Database Comn~unication 1 4.com 66 page-g--. :-. .I . O//EN1' 3 .OracleDriver</property> <mapping resource= "corn/neo/hiberna te/rnappinq/Accouli t .. <session-factory> 6. L ' . <!DOCTYPE hibernate-configuration PUBLICu-//Hibernate/Hiberna~eConfiguration DTD 3..L . P .h~ibernate. .soilrc?forge ..xml 1." ~ ~ ~ : ~ ! ~ i 3 z t 1 i ? ~ . . 8. i3!ne11>S\. '. . usernan~e">root</prope~-t.ar</property> <rnappi!?g rescurile= "co!ii/neoihiberna te/nlappii~g. ...:. 12. n e t / h i b e r n a t e .>. .. .. . G . 11. O / / E M V 3.net/hibernate-co11figuration-3.~:.cfa.^.fie. I / 1 i - 2. </hibernate-c3r..+rL:.. ~ .. . 10.n~ysql..

. identifier generation logic has implemerited by using JDBC. . how the prlrllaly key value for the new record is golng t o I generate 3 1 Hibernate using different primary key generator algorithms. > 1 <generator class="generator-class-namet'> I <param name="param-nameH>param-value</param> I </generator> I </hibernate-mapping> I I The following are the list of main generators we are using in the hibernate framework 1 1.hibernate.id.-.ldentifierGeneratorU interface.-- -riWI Generator classes > Generator classes are used to generate the 'identifier' for a persistent object.- .. 3 All Generator classes has to implement 'org.23734842 An IS0 9001 : 2000 Certified Company --- P a F 67 Ihttp://javabynataraj. The logic t o generate 'identifier' has to write in this method i > I 1 > In built-in ger\e~atorclasses.blogspot. i. assigned I 3. Ameerpet.SekharReddy -.e. seqhilo I I </class> I 1 i 1 </rd> I I Naresh i Technologies.hibernate.. Ph: 040-23746666. Satyam Theatre. which is ttie sub element of <id/> tag - > <generator/> tag has one attribute called "class" with which we can specify generator class-name. Opp. increment I 5.--- Mr. And has t o override generate() metliod. sequence 1 2. if we need t o pass anv parameters t o generator class then we ! can use <param /> tag. I i 9 While configuring <generator /> tag in mapping file.Hibernate-Generators using XML I --.com I i ..id. Hyderabad. If we want we can write the user defined generator class and it should implement 'org. 1 Example: HEM 1 <hibernate-niapp~ng> I I I ~ <class . which i s the sub element of <generator/> tag...ldentifierGenerator' interface and has to override generate() method. --. - > To configure generator class we can use <generator /> tag. While saving an object into the database. > <Id . the generator Informs t o the hibernate that. for each algorithm internally a java class is there for its implementatiorl i' .

Then where is the question of calling that f r o m hibernate applicat~on? 1 / NOTE: When we configured generator class for an entity. Ameerpet.blogspot. native 8. select 11.short types of primary keys.long. then we no need t o assign identifier value t o entity object I whiie saving the entity. ' : NOTE: MYSQL even won't allow to create SEQUENCE Object in that database.com Page682 I - . Naresh i Technologies. Opp. uuid 9 guid 10. - P Not has the support with MySq! 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 t o generate the identifier and it will assign to the Id property of persistent object. Satyam Theatre. guid are used when the pri~nary key column type is String type (varchar2) 1. Even we assign the identifier value t o entity. 23734842 An I S 0 9001 : 2000 Certified Company I -. . it will not consider our assigned value. Ph: 040-23746666. It applies t o all generator classes.SequenceGenerator) ' I I ~ > This generator class is database dependent i t means. foregin I 1 In the above generators list. http://javabynataraj. 1 Steps t o work with "sequence" Renerator ! I I 1 Step 1:Create a sequence SQL> CREATE SEQUENCE ACCNO-SEQ START WITH 1000 INCREMENT BY 1 To get next value SQL> SELECT ACCNO-SEQ.NEXTVAL FROM DUAL. we should know whether the database supports sequence or not before we are working with it -.1 6. and uuid. To get current value I SQL> SELECT ACCNO-SEQ-CURRVAL FROM DUAL. Step 2: configure the sequence in hbm file. it will use / generator class generated value as identifier value. we cannot use this generator class for all the database.hibernate.id. identify \ 1 7. Then it will store the persistent object into Database. are used for int.) sequence (or~. Hyderabad.

database objects i f they are not exist. setBalance (5000)..id.. ..getSession(). 9.. Otherwise hibernate raises the exception. Account account = new Account 5.println (flAccount is created with accno : "+id) .blogspot. 2 .. account.. - .. I 1. Session session = SessionUtil. . . 10..getTransaction ( ) . .. NOTE: But remember. . then it is ! I used by hibernate. 1 1I I i1 Step 3: Create the entity and save it without assigning identifier. --. .. \ .hibernate. .. Opp.... always prfer t o create a different sequence t o each enitity seperately. = session. . Mr. 1 - I ( I I 7. account...SequenceGenerator" > <param name="sequence">ACCNO-SEQ </param> </generator> </id> (OR) <id name=" accountld " column="ACCNO"> <generator class="sequenceU/> </ld> 1 I !I ' 1 - NOTE: If we don't configure any sequence name then i t will take default sequence name(HIl3ERNATE-SEQUENCE ). 6. Satyam Theatre. . . commit ( ) .. session.. I I 1 I 1 NOTE: It i s not advisable t o use the default sequence.auto property in hibernate configuration file.save (account). 1 4.-.. . But hibernate won't create the sequence.. -- --. Arneerpet.. setName ("sekhar") . ~ ~ d e r a b a Ph: d .. . ... if we enable hbrn2ddl.getTransaction ( ) .. 23734842 An IS0 9001 : 2000 Certified Company I 1 Page69 3http://javabynataraj.. L . 11....begin ( ) . then hibernate will create the . rims i I 1 ! 1 I - 1 <id name=" accountld " column="ACNO"> <generator class="org.. 040-23746666.out..SekharReddp Hibernate-Generators using X M.. i f already sequence i s available with name "HIBERNATE-SEQUENCE". 3. . Serializable id () . --.. 8.. I Naresh i Technologies.... System..... session. ! . -...com .

getProperty(PARAMETERS). Opp. iterate results . 23734842 An I S 0 9001 : 2000 Certified Company http://javabynataraj. rs.next().id. return result. .){ sequenceName = PropertiesHelper. . i f we do not specify <generator/> element under <id/> element.. . ) { Preparedstatement st =.. Internal Code public class SequenceGenerator implements PersistentldentifierGenerator. // default sequence name parameters = params. we can find the sequence execution query on the console. Hyderabad.getString(SEQUENCE. I HBM: <id name=" accountld " column="ACCNO"> <generator class="org.Assigned" /> </id > (OR) ! I Naresh i Technologies. . . Serializable result = .. . Configurable { public static final String SEQUENCE = "sequence".__ IVOTE: When we execute the above code. Satyam 'Theatre.SekharRecici\. then hibernate by default assumes it as "assigned" generator class.hibernate. I public void configure(. -- - -- -- - .-- Hibei-nate-Generators using XML -- Mr. then the programmer is responsible for assigning the identifier value t o entity before saving into the database 1.prepareSelectStatement(sql). you can u.com 704--' Page 1 . "hibernate-sequence").- .. Resultset rs = st. Ameerpet.executeQuery(). params. Ph: 040-23746666. 9 If generator class is assigned. which is used t o get 1 1 I identifier for the saving enitity. /I I 1 I 9 This generator supports in all the databases 9 This is the default generator class used by the hibernate. 1 1 NOTE: \\ow onwards for the following generator classes I just give the HBM configuration.e the same entity saving logic(which we used in the above example as part of step-3) t o test them.blogspot. . 1 I 1 public Serializable generate(.

.. . Ph: 040-23746666. Ameerpet. ..----. - ~ http://javabynataraj.. . get the developer glven id.. . .~ . 1 I i return id. ---~ .@<~~tJj:$?~g.lncrementGenerator " /> </id> 1 Internal Code: I public class ~.x :. identifier type in enity should be some object type rather than I primitive type. : + -*!v-.. 23734842 An I S 0 9001 : 2000 Certified Company --. I I I 1 I I <id name="accountld" column="ACCNO"> <generator class="increment" /> </id> (OR) <id name=" accountld " column="ACCNO"> <generator class=" org....: ... .. . . ...: public synchronized Serializable generate(. -%a I - <id name=" accountld " column="ACCNO" /> Internal Code: I public class Assigned implements Identif~erGenerator.. ..id..- ~ Hi bernate-Generators using XM L -- -- ' ~ ~ ~ . Hyderabad. i I HBM: . .--- ---- - . Configurable { ...:. ..~$~~~$ implements IdentifierGenerator. This generator is used for generating the id value for the new record by using the formula Max o f id value i n Database + 1 > If there is no record initially in the database. . --....5 ~ *>.1 . Opp..com P a g71 es- ...@$@. ... Whrle testing don't asslgne ident~fiervalue to entity and then try t o save entity then ~tthrows IdentifierGenerationException. ) { final Serializable id = ... . so i t is database independent generator class. iI ! I > ' I i I This generator supports in all the databases. ! NOTE: While testing with assigned generator class. .. 1 } I I NOTE.hibernate.fi nal number after adding '1' Naresh i Technologies.-r@ ~ :..-I ..<!.- 1 return .. .~ --I Mr. I 1 .. then for the first time this will saves primary key value as 1.--...-.. .- - . . i f (id==null) { throw new Identif~erGenerat~onException( "ids for this class must be manually assigned before calling save(): " t entityName)..){ I i f (sql!=null) { getNext( session ).... . Satyam Theatre. .blogspot..Conf~gurable{ public Serializable generate(...<.SekharReddy -.-.

- ~.650 can be safely allocated t o clients..) { sql = "select max(" + column + ") from " + buf.. while the size of this series is donated by the l o w value.769.736. 23734842 An IS0 9001 .- -3 . once the entire series has been exhausted the algorithm goes back t o step 1 2) 3) 4) I I 1 I 6' 1 I I I I I Example: suppose that the current high value in the database is 52 and the low value i s configured t o be 32.736.~.884 Upper bounds = 1. .getLong(1) + 1..651 Upper bounds = 1. Hi bernate-Generators using XML .next() ) { next = rs.p repareSelectStatement(sql).767-1= 1.Sel<harReddy_-.- ~ 1 ~ ~ -.toString(). This time the h i i h value is 53 (immediately incremented t o 54) and the keys range is: 1 I Lower bound = 53*32.767.703. -Ihe high value is used as a base for a series (or range) of numbers.. .com 726 Page _I- .736. public void configure(.. Based on the low I I 1 II I IVaresh i Technologies. -.650 I I 1 1 All o f the numbers in the range of 1. I private void getNext( Sessionlmplementor session ) { ! Preparedstatement s t = . Ameerpet.blogspot. The range of the current numbers series can now be calculated: Lower bound = 52*32767 = 1. the result is the first number (lower bound) of the current series The l a s t number (higher bound) of the current series is donated by the following calculation: (max*low)+low-1 When a client needs t o obtain a number the next one from the current is used.884 t o 1.767-1 = 1. Resultset rs = st. Ph: 040-23746666. Mr.: 2000 Certified Company http://javabynataraj. Satyam Theatre.executeQuery(). if ( rs.651+32. When the algorithm starts is loads the high value from the database and increments it in the same transaction (the new high value in the database is now 53). . once this keys pool has been exhausted the algorithm needs t o access the database again t o allocate a new keys pool. Opp.. 1 1 I 1I ' / The HiLo Algorithm - The HiLo (High/Low) algor~thmknows how to generate unique number series using t w o values: the high and the low.703. A unique series is generated using the following steps: 1) Load the and atomically increment the high value Multiple the high value by the low value (max*low).703. Hyderabad.736.--.767 = 1.884+32.417 And so on The big advantage of this algorithm is keys preallocation which can dramatically improve performame.

com .t h e table name. . Opp. It supportsthe following parameters: o o o o . Ameerpet.the table name. This is useful when we need each entity (or some of the entities) has its own keys range. Satyam Theatre..-- -.767 generated keys. 23734842 An IS0 9001 : 2000 Certified Company Page73 7 http://javabynataraj.key column name.- . default t o the entity's primary table name primary-key-length . Seq uenceHiLoGenerator TableHiLoGenerator A simple HiLo generator. The generator accepts the following parameters I o table . Hibernate has several HiLo based generators: TableHiLoGenerator.length of the key column in DB represented as a varchar.the low number (the range) defaults t o 32.the name of the column to store the next high value.t h e name o f the column t o store the next high value. when having multiple entities using the same generator Hibernate matches an entity t o a high value using the primary-key-value which is usually the entity name.767 (Short.- -- Hibernate-Generators using XM L ' .Seltl?arReddy value we can control the database hit ratio. uses a table t o store the HiLo high value. Ph: 040-23746666.blogspot. defaults t o 'sequence-next-hi-value' primary-key-value . Hyderabad.-- - -. A sample table can look like Naresh i Technologies. . defaults t o 255 max-low .- -- - --.MAX-VALUE) I I I I I The generator uses a single table t o store multiple high values (multiple series).767 we hit the database only once in a 32.but in my opinion this is a none-issue) is that each time t h e algorithm restarts it leaves a 'hole' in the keys sequence. MuItipleHiLoPerTableGecierator. default t o 'hibernate-sequences' primary-key-column . .767 (Short.-- - -- -- --- - M1-.-- --. / o o table . defaults t o 'sequence-name' value-column . defaults t o 'hibernate-unique-key' column . As illustrated using the 32.key value for the current entity (or current keys set). defaults t o 'next-hi' I o o I max-low .the low numer (the range) defaults t o 32. The downside (at least by some people .MAX-VALUE) i ! I 1 A table HiLogenerator which can store multiple key sets (multiple high values each for a different entity).

-pp--p----.. String DEFAULT-TABLE-NAME = "hibernate-unique-key".---pp- .blogspot.. o o sequence . .. 23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj. .Sel<harRecldv'1 r Hibernate-Generators using XM L A simple HiLo generator but instead o f a table uses a sequence as the high value provider.com 748 Page I I I I .... Ph: 040-23746666.. r ... where as seqhilo generator stors its high value i n sequence. Default table is 'hibernate-unique-key' column is 'next-hi'. Satyam Theatre.. String TABLE = "table"... II 1 3 It is just like hilo generator class. IVaresh i Technologies.. Ameerpet.-. defaults t o 'hibernate-sequence' This generator is database independent hilo uses a hi/lo alogorithm t o generate ~ d e n t ~ f ~ e r s .. Opp. Hilo algorithm generate identifiers based on the given table and column(stores high value).the low number (the range) defaults t o 9. ... Hyderabad....~ . But hilo generator stores its high value in table.~ . String DEFAULT-COLUMN-NAME = "next-hi". I HBM: I < ~ name="accountld" d column="ACCNO"> I .. MI-.. L.....the sequence name. I ! <generator class="hilo" > <param name="table">HIGH-VAL-TAB</param> <param ndme="column">HIGH-VAL-COL</param> Internal code class TableHiLoGenerator extends TableGenerator { I I 1 I i i class TableGenerator { public static final public static final public static final public static final i String COLUMN = "column".. r 1 r max-low .

SequenceHiLoGenerator ">ACCNO-SEQ</param> <param name="max-lo">5</param> 1 </id> 1 </generator> Q.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. Ameerpet. . MYSQL. SQL SERVER. .. ~~ ~ -~~ Hibernate-Gelieratol-s using X M L . COURSE CHAR(2O).) How t o work w i t h MYSQL database? a install the MYSQL database.blogspot. Mr.. ..S E Q < / p a r a m > <param name="max-lo">S</param> </generator> </ld> (OR) i <id name=" accountld " coiumn="ACCNO"~ <generator class="seqhiloU > <param name="org.-- . 9 9 9 This is database dependent. c3 When we login t o database next time onwards don't give create database command..--. c3 Select All Programs 3 MYSQL 3 MYSQL 5. PRIMARY KEY (SNO) 1 -- 1 HBM: <id name=" accountld " column="ACNO"> <generator class="identity" /> </id> / Example: To create identity columns in MYSQL database. . just give use command.com I ! : I . 23734842 An I S 0 9001 : 2000 Certified Company p a g e75 9 -http://javabynataraj. NAME CHAR(20). Identity columns are support by DB2. This identity generator doesn't needs any parameters t o pass Syntax t o create i d e n t i t y columns in MYSQL database: CREATE TABLE STUDENT( SNO INT(10) NOT NULL AUTO-INCREMENT. Ph: 040-23746666.. actually it's not working in oracle.id.-~ ~~ ~ . Satyam Theatre.~ ~~ -. SYBASE and HYPERSYNCSQL databases. 1 I I --. Opp.hibernate. 1 I Naresh i Technologies. FEE FLOAT.. Hyderabad.SeltliarReddg7 HBM: - <id name="accountld" column="ACNO"> <generator class="seqhilo" > <param n a m e = " s e q u e n c e " > ~ ~ ~ ~ ~ .

Hyderabad. 23734842 An I S 0 9001 : 2000 Certified Company I I -1 http://javabynataraj. Ameerpet..blogspot. Satyam Theatre. ~ e k h a r.- - -- .-.) native I 3 native i s not having any generator class because. Ph: 040-23746666. it uses internally identity or sequence or hilo generator classes. P native picks up identity or sequence or hilo generator class depending upon the capabiliti2s of the underlying database.com Page 76 10 . ~ eI d d '- 7.. Opp...-- Hibernate-Generators using XML - - -- - - ---. I * I I - H BM: <id name="accountld" column="ACIVO"> IVaresh i Technologies.---- -- ~ i .

Opp. 1 C3 uuid algor~thmencodes identifier as a string(hexadecima1 digits) of length 32. then we will go for user defined generator class. C3 If we connect to oracle it takes sequence. .. d uuid generated identifier i s unique with in a network.UUIDHexGenerator " > </generator> </id> 1 retrieving the primary key value. In this I method implement the identifier generation logic as per the requirement. C3 Generally uuld is used t o generate passwords. i Steps t o implement user defined generator class.com 77 Page 11 I I I -.IdentifierGenerator and override generate() method. I guid: uses a database generated guid string on MS-SQL and MYSQL. Ph: 040-23746666. Hyderabad.blogspot.<id name="accountld" column="ACNO"> ~ <generator class="uuid" > </generator> - </id> 1 ' <id name=" accountld " column="ACCNO"> <generator class="org. I foreign: foreign uses the identifier o f another associated object. XML 1 I I I NOTE: test with niysql and oracle C3 If we connect to mysql i t takes identity.hibernate. Usually uses in conjunction with a <one-to-one> primary key association. 23734842 An IS0 9001 : 2000 Certified Company http://javabynataraj.id.Hibernate-Generators using.b ~uuid t algorithm t o generate identifiers of type string. - I select: select retrieves a primary key assigned by a database trigger by selecting the row by some unique key and I I 1 I I User Defined G e n e r a t o r class - I I 1 When we feel the existing generator classes are not fit for our requirement. Satyam Theatre. 1 HBM: .. d uuid uses a 1 2 8 .- . I c3 uuid algorithm generates identifier using IP address. Naresh i Technologies.id . i 1 I I I 1 Step 1:Take any java class and implement org. Ameerpet.hibernate.

blogspot.http://javabynataraj.com 78 .

blogspot.http://javabynataraj.com 79 .

http://javabynataraj.blogspot.com 80 .

http://javabynataraj.blogspot.com 81 .

http://javabynataraj.blogspot.com 82 .

com 83 .blogspot.http://javabynataraj.

com 84 .http://javabynataraj.blogspot.

http://javabynataraj.com 85 .blogspot.

http://javabynataraj.blogspot.com 86 .

http://javabynataraj.blogspot.com 87 .

blogspot.com 88 .http://javabynataraj.

com 89 .http://javabynataraj.blogspot.

http://javabynataraj.com 90 .blogspot.

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

com 97 .http://javabynataraj.blogspot.

blogspot.com 98 .http://javabynataraj.

http://javabynataraj.blogspot.com 99 .

blogspot.http://javabynataraj.com 100 .

http://javabynataraj.com 101 .blogspot.

com 102 .http://javabynataraj.blogspot.

http://javabynataraj.blogspot.com 103 .

com 104 .http://javabynataraj.blogspot.

blogspot.com 105 .http://javabynataraj.

http://javabynataraj.blogspot.com 106 .

blogspot.com 107 .http://javabynataraj.

blogspot.com 108 .http://javabynataraj.

http://javabynataraj.com 109 .blogspot.

http://javabynataraj.blogspot.com 110 .

http://javabynataraj.com 111 .blogspot.

blogspot.com 112 .http://javabynataraj.

com 113 .http://javabynataraj.blogspot.

com 114 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 115 .

com 116 .http://javabynataraj.blogspot.

blogspot.http://javabynataraj.com 117 .

blogspot.http://javabynataraj.com 118 .

http://javabynataraj.com 119 .blogspot.

blogspot.com 120 .http://javabynataraj.

blogspot.http://javabynataraj.com 121 .

com 122 .blogspot.http://javabynataraj.

http://javabynataraj.com 123 .blogspot.

blogspot.http://javabynataraj.com 124 .

http://javabynataraj.com 125 .blogspot.

blogspot.com 126 .http://javabynataraj.

com 127 .http://javabynataraj.blogspot.

http://javabynataraj.blogspot.com 128 .

com 129 .blogspot.http://javabynataraj.

http://javabynataraj.com 130 .blogspot.

blogspot.com 131 .http://javabynataraj.

http://javabynataraj.com 132 .blogspot.

com 133 .http://javabynataraj.blogspot.

com 134 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 135 .

blogspot.com 136 .http://javabynataraj.

blogspot.com 137 .http://javabynataraj.

blogspot.http://javabynataraj.com 138 .

com 139 .http://javabynataraj.blogspot.

com 140 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 141 .

com 142 .blogspot.http://javabynataraj.

com 143 .http://javabynataraj.blogspot.

com 144 .blogspot.http://javabynataraj.

blogspot.com 145 .http://javabynataraj.

http://javabynataraj.com 146 .blogspot.

blogspot.com 147 .http://javabynataraj.

com 148 .blogspot.http://javabynataraj.

blogspot.com 149 .http://javabynataraj.

http://javabynataraj.blogspot.com 150 .

blogspot.http://javabynataraj.com 151 .

com 152 .blogspot.http://javabynataraj.

com 153 .http://javabynataraj.blogspot.

com 154 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 155 .

com 156 .http://javabynataraj.blogspot.

blogspot.http://javabynataraj.com 157 .

com 158 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 159 .

com 160 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 161 .

com 162 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 163 .

blogspot.http://javabynataraj.com 164 .

com 165 .blogspot.http://javabynataraj.

blogspot.com 166 .http://javabynataraj.

blogspot.com 167 .http://javabynataraj.

blogspot.com 168 .http://javabynataraj.

http://javabynataraj.com 169 .blogspot.

http://javabynataraj.blogspot.com 170 .

http://javabynataraj.blogspot.com 171 .

com 172 .http://javabynataraj.blogspot.

blogspot.com 173 .http://javabynataraj.

com 174 .blogspot.http://javabynataraj.

com 175 .blogspot.http://javabynataraj.

com 176 .blogspot.http://javabynataraj.

blogspot.com 177 .http://javabynataraj.

com 178 .blogspot.http://javabynataraj.

com 179 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 180 .

com 181 .blogspot.http://javabynataraj.

com 182 .http://javabynataraj.blogspot.

http://javabynataraj.com 183 .blogspot.

blogspot.http://javabynataraj.com 184 .

com 185 .http://javabynataraj.blogspot.

http://javabynataraj.blogspot.com 186 .

blogspot.com 187 .http://javabynataraj.

http://javabynataraj.blogspot.com 188 .

http://javabynataraj.blogspot.com 189 .

blogspot.com 190 .http://javabynataraj.

blogspot.com 191 .http://javabynataraj.

blogspot.http://javabynataraj.com 192 .

http://javabynataraj.blogspot.com 193 .

com 194 .http://javabynataraj.blogspot.

blogspot.http://javabynataraj.com 195 .

com 196 .http://javabynataraj.blogspot.

com 197 .http://javabynataraj.blogspot.

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

blogspot.http://javabynataraj.com 204 .

http://javabynataraj.com 205 .blogspot.

blogspot.http://javabynataraj.com 206 .

com 207 .blogspot.http://javabynataraj.

com 208 .http://javabynataraj.blogspot.

http://javabynataraj.com 209 .blogspot.

com 210 .http://javabynataraj.blogspot.

http://javabynataraj.blogspot.com 211 .

com 212 .http://javabynataraj.blogspot.

com 213 .http://javabynataraj.blogspot.

blogspot.http://javabynataraj.com 214 .

http://javabynataraj.com 215 .blogspot.

blogspot.http://javabynataraj.com 216 .

com 217 .blogspot.http://javabynataraj.

com 218 .blogspot.http://javabynataraj.

http://javabynataraj.com 219 .blogspot.

http://javabynataraj.blogspot.com 220 .

http://javabynataraj.blogspot.com 221 .

com 222 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 223 .

http://javabynataraj.blogspot.com 224 .

http://javabynataraj.com 225 .blogspot.

com 226 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 227 .

com 228 .http://javabynataraj.blogspot.

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.com 235 .blogspot.

com 236 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 237 .

http://javabynataraj.blogspot.com 238 .

blogspot.com 239 .http://javabynataraj.

blogspot.com 240 .http://javabynataraj.

com 241 .http://javabynataraj.blogspot.

blogspot.com 242 .http://javabynataraj.

com 243 .http://javabynataraj.blogspot.

com 244 .http://javabynataraj.blogspot.

blogspot.http://javabynataraj.com 245 .

http://javabynataraj.com 246 .blogspot.

http://javabynataraj.com 247 .blogspot.

com 248 .http://javabynataraj.blogspot.

http://javabynataraj.blogspot.com 249 .

blogspot.com 250 .http://javabynataraj.

blogspot.com 251 .http://javabynataraj.

blogspot.http://javabynataraj.com 252 .

blogspot.com 253 .http://javabynataraj.

blogspot.http://javabynataraj.com 254 .

com 255 .http://javabynataraj.blogspot.

http://javabynataraj.blogspot.com 256 .

com 257 .blogspot.http://javabynataraj.

blogspot.com 258 .http://javabynataraj.

blogspot.com 259 .http://javabynataraj.

http://javabynataraj.blogspot.com 260 .

com 261 .http://javabynataraj.blogspot.

http://javabynataraj.com 262 .blogspot.

blogspot.http://javabynataraj.com 263 .

http://javabynataraj.blogspot.com 264 .

com 265 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 266 .

blogspot.http://javabynataraj.com 267 .

com 268 .blogspot.http://javabynataraj.

com 269 .http://javabynataraj.blogspot.

blogspot.com 270 .http://javabynataraj.

blogspot.com 271 .http://javabynataraj.

com 272 .http://javabynataraj.blogspot.

blogspot.http://javabynataraj.com 273 .

blogspot.http://javabynataraj.com 274 .

blogspot.http://javabynataraj.com 275 .

http://javabynataraj.blogspot.com 276 .

blogspot.com 277 .http://javabynataraj.

com 278 .blogspot.http://javabynataraj.

com 279 .http://javabynataraj.blogspot.

blogspot.com 280 .http://javabynataraj.

com 281 .blogspot.http://javabynataraj.

com 282 .http://javabynataraj.blogspot.

com 283 .blogspot.http://javabynataraj.

com 284 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 285 .

com 286 .http://javabynataraj.blogspot.

blogspot.com 287 .http://javabynataraj.

http://javabynataraj.blogspot.com 288 .

com 289 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 290 .

http://javabynataraj.com 291 .blogspot.

http://javabynataraj.blogspot.com 292 .

http://javabynataraj.blogspot.com 293 .

blogspot.http://javabynataraj.com 294 .

blogspot.com 295 .http://javabynataraj.

com 296 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 297 .

http://javabynataraj.com 298 .blogspot.

com 299 .http://javabynataraj.blogspot.

com 300 .http://javabynataraj.blogspot.

blogspot.com 301 .http://javabynataraj.

http://javabynataraj.blogspot.com 302 .

blogspot.com 303 .http://javabynataraj.

http://javabynataraj.blogspot.com 304 .

http://javabynataraj.com 305 .blogspot.

blogspot.http://javabynataraj.com 306 .

http://javabynataraj.com 307 .blogspot.

com 308 .blogspot.http://javabynataraj.

http://javabynataraj.blogspot.com 309 .

com 310 .http://javabynataraj.blogspot.

http://javabynataraj.com 311 .blogspot.

blogspot.com 312 .http://javabynataraj.

com 313 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 314 .

com 315 .blogspot.http://javabynataraj.

blogspot.com 316 .http://javabynataraj.

blogspot.http://javabynataraj.com 317 .

blogspot.http://javabynataraj.com 318 .

blogspot.com 319 .http://javabynataraj.

http://javabynataraj.blogspot.com 320 .

blogspot.com 321 .http://javabynataraj.

blogspot.http://javabynataraj.com 322 .

blogspot.http://javabynataraj.com 323 .

com 324 .blogspot.http://javabynataraj.

blogspot.http://javabynataraj.com 325 .

http://javabynataraj.com 326 .blogspot.

blogspot.com 327 .http://javabynataraj.

com 328 .http://javabynataraj.blogspot.