Hibernate Complete
Hibernate Complete
com
A Perfect Place for All Java Resources
www.JavaEra.com
A Perfect Place for All Java Resources
Hibernate
www.JavaEra.com
.-. -. pp.pp.--p.- ... -. . . . . - ..
~ ~
. -
1, Hibernate-Introduction M r.Sek11arReddy
- - -.
x.
I
Controller Layer
I
Client Layer
-. Presentation I
I
I
J : -
Layer
1
I
I
1 Client Layer:
I
3 It is browser software.
i
1 Controller Layer:
1
I
P Receiving user request from client (calling request)
> Capturing the user provided data
P Validating the user input
1 Calls the business method t o get business services and get processed data
>
Ii >
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
Presentation Layer:
Business/Service Layer:
1I Naresh i Technologies, Opp. Satyam Theatre, Anleerpet, Hyderabad, Ph: 040-23746666, 23734842
L-- - -.-- --- -
An IS0 9001 . 2000 Certified -
---..---
Company
. - - -- - - .- -- - .- -- --- --.
- -
Page 1
-
. , -.- . ..- -- L-- .
.- - i
PersistentIData-Access Laver:
i Receiving the request from business Layer
I P Contacting database to get the database data
O Return the accessed data t o business Layer
I
Data Laver:
1 > It is a database.
-
I
Application/Controlling Logic: Logic used t o control the flow of application. I
/
1
I
Business Logic: Programmatical implementation of business rules is nothing but business logic. j
Data Access Logic: Logic used t o contact the Database.
-
I
Q) What are t h e Sun Microsystems technologies and frameworks in enterprise application development?
.'
I
'I /
I
Controller Layer
Servlets
JSF
Presentation Layer
JSP
t
Business Layer
EJB2 session beans
EJB3 session beans
WIDB(Message Driven
Data Access Layer
JDBC
Ejb2 entity beans
Ejb3 entitys[JPA ] (java
Beans) persistence API)
' WEB-SERVICES
L--. -.
.- -- - -
An..-
IS0
.- -
9001 : 2000 Certified-Company
-- - -- --
-. .
Page 2 -
1
, Hibernate-In troduction
'
Q) What is persistence i n a java based enterprise application?
!
I > 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 Application portability t o the Database is lost (Vendor lock: diff SQL statement for the db's)
1
3 Mismatches between Object oriented data representation and relat~onaldata representation are not
I
I properly addressed
I
I
3 Requires the extensive knowledge of DB
I
I
I
P Manual operations on Resultset 7
I
I
v For every problem while commun~catingwith the database (us~ng
JDBC), it throws same
-
I
I
exception(java.sql.SQLException). As SQLException is checked exception, so we must write code in try-
,
;
I catch block or throws has t o be specified.
I
I
> Need t o implement caching manually iI
I
3 In the Enterprise applications, the data flow with in an application from class to class will be in the 1
form of objects, but while storing data finally in a database using JDBC then that object will be I
> 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?
-
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An I S-0 9001 : 2000 Certified Company
-- I
Page 3
~ ~ ~ ~ ~~ ~. ~-~ . ~ ~ ~~ ~ .~~ .
A frameworl< is reusable semi finished application that can be customized t o develop a specific
application.
i 9 Hibernate generates efficient queries for java application t o communicate with Database i
I ,
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 3 it supports synchronization between in-memory java objects and relational records
I
> Hibernate provides implicit connection pooling mechanism !
I j
Hibernate supports Inheritance, Associations, Collections
I 3 Hibernate supports a special query language(HQL) which is Database vendor independent
1 9 Hibernate has capability t o generate primary keys automatically while we are storing the records into /
database i
1
1
>
>
Hibernate addresses the mismatches between java and database
Hibernate provides automatic change detection
1I
I
9 Hibernate often reduces the amount o f code needed t o be written, so it lrnproves the productivity I
I i
I
> Database objects (tables, views, procedures, cursors, functions ...etc) name changes will not affect
I hibernate code I
i
iI 3 Hibernate provides transactional capabilities that can work with both stand-alone or java Transaction 1
1 API (JTA) imple~nentations...etc .
,
.
I
I
I
I
i Hibernate supports annotations, apart from X M L
I
,
II
Q.)What are the disadvantages of hibernate? 1
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 understanding of conlposite mapping is complex
/ P Hibernate does not support some type of queries which are supported by JDBC
1 9 Boilerplate code issue, actually we need t o write same code in several files i n the same application, ,'
I but spring eliminated this I
I
1
1 Hibernate Architecture
n
1
java application
A \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
'./
Data base
1
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
I-,
1l-
mapping file and configuration file information. I
I
I
i 1
iL_. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
- _ - __--
An IS0 9001 : 2000 Certified Company
- .-
.-- - -
(
I
1
Page 5
-. . . . . . . . . . . . . . . . . . . . .
JTA JNDl
...r...*.-......
.
&.
~
.>** ..&..."..,
.."*"? f .. *..-.-...'*..." -. . . . . . . . . . . . . . . .
I -- I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i
An IS0 9001 : 2000 Certified Com~anv I
Page 6
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 " />
1 4.
1 5. < 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 " />
1 6. < 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 " />
' 7 . </class>
I 8.
, 9 . </hibernate-rnapplng>
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 t
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.
I
No. of databases we are using = That many number of configuration files I
I
( > We don't have annotations t o write configuration details. Actually in hibernate l.x, 2.x we defined this j., \
1
I
configuration by using .properties file, but from 3.x XML came into picture. XNlL files are
1
' 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
i
data is done in this f ~ l e I
i Z Standard name for this file is <domain-object-name.hbm.xml> I
I
r In general, for each domain object we create one mapping file
I Number of Entity classes = that many number of mapping xmls
I Z Mapping can be done using annotations also. If we use annotations for mapping then we no need t o I
write mapping file.
I
Z From hibernate 3.x version on wards it provides support for annotation, So mapping can be done in
t w o ways
o XML
o Annotations
'
I
1 1 Entity class
2 . Mapping file(Required if you are not using annotations)
i 3. Configuration file
4. DAO class (Where we write our logic to work with database)
I
I1 i
Setting hibernate environment
;To work with hibernate framework we need t o add .jar(s) files provided by that framework to
I
I
'
I j our java application.
I 'i When we download any framework, we will get a 'zip' file and we need t o unzip it, to get the required 1.
i
jar files, actually all frameworks will follow same common principles like ... 1
j
!
o Framework will be in the form of a-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.
i
> We can download hibernate jar files from the following links. Based on requirement we can download
the corresponding version.
o For version 2.x (http://sourceforge.net/projects/hibernate/files/hibernate2/)
o For version 3.x (http://sourceforge.net/proiects/hibernate/f1les/hibernate3/)
o For version 4.x (http://sourceforge.net/projects/hibernate/f1Ies/hibernate4/)
> While dowr~loadingselect .zip file for windows environment, select .tar flle for unix environment. 1
j
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1:
I
An IS0 9001 : 2000 Certified Company - --- 1
Page 9
- - Hibernate-Introduction
After downloading the zip file, unzip it and we can find the required jars in the extracted folder. If we consider
4.x version, we need the following jars to work with hibernate application.
NOTE: Along with the hibernate jars we must include one more jar file, which is nothing but related to our database, this
, is depending on your database. For example, if we are working with Oracle we need 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?
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();
I
SessionFactory factory = configuration.bhildSessionFactory();
!-
STEP4: Get Session f r o m SessionFactory object
Session session = factory.openSession();
I
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
- -- --
Page 10-
Hibernate-Introduction
The Session interface provides methods t o perforni CRUD (Create Read Update Delete) operations o n
,.. -
i
I the instances of mapped entity classes. Perform transactions if require while performing D M L : : I
-
I
. .
-
ses$;it:~n 1.19date1:s: LJ:.~.cl~!it-~ci
object ' sit1 t h e ~ : l a t a b a s e I
Sa:ssiul-1
TI-ansaction
Close Statet?lents
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,
NAME VARCHAR2 (20) NOT NULL,
BA L NUMBER(8,2) NOT NULL,
CREATION-DT DATE NOT NULL,
PRIMARY KEY ( ACCNO )
1
i ACCOUNT TABLE
E: :-'.L CREAT IOI I-DT
J . - .. - .
fiP541.07J ':74>:7illi
! 91:1U02 yellari.diis; E:i;5d$.69 5;'15;21:112
gDlli13 clierr-,!
-
-ac(-iS?.?6 5,,'2!2l:l12
I
hibernate.cfg.xml
I
1 1 . <?xml version='l.O1 encoding='UTF-8'?>
2 . <!DOCTYPE hibernate-configuration PUBLIC
I 3.
4.
"-//Hibernate/Hibernate Configuration DTD 3.0//ENM
"http:/>hibernate.sourceforge.net/hibernate-configuration-3.0.dtdIT>
--- -- I
I
I
I
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified Company
---- -
p a s -
, . -~. .- -~ ~ - .. . .. - - ~ ~.~ ~ ~~ ~ . . . ~~ I -\
: Hibernate-CRUD-Application
-
. .
... -.
------.
..-. ..
- -- --.-....,.-&.c3-..-.-...
By -Mr.
.- -- -
- -
.---
.
SekharReddy
-,..YLT
-. . -
-; -- .
I
"< .yr*r- ,-
u_
,.: %
.
j 14. </property>
! 15. .-y ,,./
,;...!-:--
,: -. .. ,.
.,.- ., . . ~" -.-.!!~;.c:ion. username">systi:n~<:prop~r~~->
j 16. < p r o p e r t ; . ::!I:!?-" ::ci!!.!?c:?.on. p a s s i i o r d " > t i q e r < i p r o p e r t ; . : -
1 17. <prop?rt:;: n :;:I.-2-"<::.::!?i:?ction.d r i v e r -c l a s s " >
j 18. G : ? z . : . e . :.;:::. :!river. OraclsDri~re~
I 19. ',i ~ J L ~ . , , i;;
~ :
; 20. , -- . -- ;-- . . -.
.>,%73, - -. . : . ! i e c t i o n .p o o l s i z e n > l5.. , i-,rpei:t;::
tc
-
1 21. ; P r o p e r :.,. ;, -..,..= ":.I -. s c l l " > t r u e < / p r o p e r t . -
i 25. <~nappLngre~~~ur~:~="c~~m/sekharit/hibsrnate/mappitig/Ar-cc~ur: t .
1 26. </session-factor;-:.
1 27.
I
i 28. </hibernate-configura:~311:.
j 29.
I
j SessionUtil.iava
1, package corn.sekharit.hibernate.ur;il;
1 2.
3. import org.hibernate.Session;
1 4. import org.hibernate.cfg.Configuration;
1 5.
1 6. public class SessionUtil {
1 7.
1 8. private static final ThreadLocaI<Session>threadLocaI = new ThreadLocaI<Session>();
I
11. static {
j 12. try { .
i
1 ii } catch (Exception e) {
1
"com/sekharit/hibernate/config/hibernate.cfg.xmI").buildSessionFactory();
e.printStackTrace();
-
Ir
1
1. . .
11 18,
19.
20.
}
private Sessionutilo {
j
I
21. }
1 22.
I
I
23.
24.
public static Session getThreadLocalSession() {
Session session = (Session) threadLocal.get(); II
25.
26.
27.
if (session == null) {
session = sessionFactory.openSession();
j11 _
!
28. threadLocaI.set(session);
!
29. }
!1 :;: 30.
}
. return session; 1
I
:,
33. ?I
I
I
34.
public static void closeThreadLocaISession() {
I
!
!,
if (session != null) {
session.close();
1
1
public static Session getsession() (
return ses~ionFactory.openSession();
1
public stat~cvoid closeSession(Sessionsession) {
if (session != null) {
session.close();
1
1
--
,
Account.java
1. package com.sekharit.hibernate.bean;
I
- 2.
/ 3. import java.ut~l.Date;
4.
1 5. public class Account {
6. private long accno;
1 7. private Str~ngname;
8. private double balance;
private Date creat~onDate;
I9.
10.
,11. public long getAccno() {
return accno;
1
public void setAccno(long accno) {
this.accno = accno;
1
public String getName() {
return name;
1
public void setName(String name) {
24. this.narne = name;
I 25. )
26.
1 27, public double getBalance() {
28. return balance;
I
I 29. 1
1
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
An IS0 9001 : 2000 Certified Company
page~---'
[--?
-- . .- - - - -- . . -- .-- - .- ~ ..- . . - ~~ , -.\
I Hibernate-CRUD Application
. - - -- --- .-. - ... -
By Mr. ~ e k h a-
r ~ e- d d ~
.. .
,..
!
. --..S.ly.-. -- ~ .< ,
----.U
-- .-\
1 30.
1
!
31.
32.
33.
public void serBalance(double balance) {
1
this.balance = bala~ce;
1
40. this.cr?ationDate = creationDate;
41. }
42.
43. @Override
1 44. public String tostring() {
1 45.
46.
return "Account [accno='! t accno + ", balance=" + balance
+ ", creationDate=" + creationDate + ", name=" + name + "I";
1 47.
48. I
}
Account. hbm.xml
1. <?xml version="l.O" encoding="UTF-8"?>
,
</id>
<property name="nameUtype="stringM >
10. <column name="IUAMEUlength="2OVnot-null="trueV ></column>
11. </property>
12. <property name="balanceUtype="doubleU >
13. <column name="BALNprecision="8" scale="2" not-null="trueN></column?
14. </property>
15. <property name="creationDate" type="dateM>
16. <column name="CREATION-DT" not-nllll="true" ></column>
17. </property>
18. </class>
19. </hibernate-mapping>
AccountDAO.iava
1. package com.sekharit.hibernate.da0;
2.
3. import 0rg.hibernate.HibernateException;
4. import org.hibernate.Session;
5. import 0rg.hibernate.Transaction;
1 ::
1
import com.sekharit.hibernate.bean.Account;
8. import com.sekharit hibernate.util.5essionUtil;
9.
10. pcrbl~cclass AccountDAO {
3 1. ( ~ u b l l Account
c get(long accno) {
12.
13. Sess1011session = null;
, 14. Account account = null;
15. try {
I 16. session = SessionUtil.getSess~on();
I 17. account = (Account) session.get(Account.class, accno);
, 18. } catch (HibernateException e) {
I 19. e.printStackTrace();
20. } f~nally{
1 21. SessionUtil.closeSession(session);
22. 1
1 23.
24. return account;
j 25. }
26.
27. p u b l ~ cv o ~ d~nsert(Accountaccount) {
i 28.
1 29. Session session = null;
I30. try {
7 31. session = SessionUtll.getSession();
I 32. session.getTransaction().begin();
33. session.save(account);
134. session.getTransaction().cornm~t();
35. } catch (HibernateException e) {
136. session.getTransaction().rolIback();
37. e printStackTrace0;
138. } f~nally{
39. SessionUtil.cl~seSession(session);
1 40. }
I 41. }
42.
I 43. p u b l ~ cvoid update(Acc0unt account) {
44. Session session = null;
I 45. try {
46. session = SessionUtil.getSession();
1 47. sess~on.getTransact~on(). beg~n();
48. session.update(account);
1 49. session.getTransaction().comrnit();
50. } catch (HibernateException e) {
( 51. session.getTransaction().rollback();
-- 52. e.printStackTrace();
I 53.
54.
} f~nally{
SessionUtil.closeSession(session);
55. 1
I 56. }
57.
1 58. public void delete(long accno) {
i AccountService.iava
I 1. package com.seltharit.hibernate.service;
3. import java.util.Date;
I1 5.
6.
import corn.sekharit.hibernate.bean.Account;
import corn.sel~harit.hibernate.dao.AccountDA0;
/ 7.
8. public class Accountservice {
9. public static void main(String[] args) { -
I
10. AccountDAO dao = new AccountDAO();
11.
12. // Retrieve Account
13. Account rAccount = dao.get(90001);
1 ::: 14.
17.
Svstern.out,println("Account details ....");
Systern.out.println("Accno : " + rAccount.getAccno());
System.out.println("Name : " + rAccount.getName());
System.out.println("8alance : " + rAccount.getBalance());
1 18.
19.
20.
Systern.out.println("Creation Date: " + rAccount.getCreationDate());
// Create Account
21. Account cAccount = new Account();
22. cAccount.setAccno(90005);
23. c~ccount.set~ame("sekhar");
24. cAccount.setBalance(6899);
25. cAccount.setCreationDate(new Date());
1 26. dao.insert(cAccount);
1 27. System.out.println("Account created successfully");
I
28.
29. // Update Account
30. Account uAccount = new Account();
31. uAccount.setAccno(90003);
32. uAccount.setName("sekhareddy");
; ;
t I:i.:a>, ?:-eddy 69541.03 5: 29,'21:1!::
9l:ll:lOj ~e\;tllll-edjj' 45i10 j!Z?jLI:l]z
!21:11:105 5el:hal- 6Sgg 5 2 9 j i C 1 1 2
d . . * cctn.rtkb~arit.hih~rnatr.utiI
'
. .:
:.i Ser-~ian!JtiI,~a~.~a
,. . .
r-:.
:,.-J. JRE S y . ~ t i i Li ~i b r a y ,...;;a::,:. . ,
--
...... H i t x r n a t e 3.3 Annctation': F,t Entit!. I:;lanagel
i,. Hitlel-nate 3.3 C n r e Libraries
LI ~ i Rj e f e r ~ t i c e dLihrariel:
080 c<clbclJ,jar
lib
3 . . ,.
1 .
hibernate.cfg.xml
.
: 1. <?xml version='l.O' encoding='UTF-8'?>
1 2 . <!DOCTYPE hibernate-configuration PUBLIC
-- 3. "-//Hibernate/Hibernate Configuration DTD 3.0//ENn
4. "http://hibernate.sourceforge.net/hibernate-configuration-3.O.dtd"~
I 5.
6. <hibernate-configuration>
8. <session-factory>
9. <property.... / >
............
i1 - Hibernate-CRUD Application --
By Mi-.
Sekhal-lieddy.-:- ,
/ -. . -.'%-*au#A&.Lcas* -*=--&= i
I
~' -,
; 23. 1
24. 'A
' 27. }
1 28. I?
41. } 1
1 42.
/
,
1
j
I
43. public void set~alance(doublebalance) { I
47. @TemporaI(TemporaIType.DATE)
I !
1
i
I 48.
49.
50.
@Column(name = "CREATION-DT", nullable = faise)
public Date getSreationDate() {
return creationDate;
.,
\
1 I
\
.
,
51. } i-
52.
h
1, :.
53. public void setCreationDate(Date creationDate).{ ,I* .
!
54; this.creation[>ate = creationDate; 1.-
55. }
1
I
56. i
1
57. @Override
1
1
58. public String tostring() {
59. return "Account [accno=" t accno + ",balance=" + balance 1,
"I"; l~
1
60. t ",creationDate=" + creationDate + ", name=" + name +
61. } i
:I1
62.
, 63. 1
Account.hbm.xml
---NOT REQUIRED--- \-
I,
AccountDAO.java !
I,
---Same As Above--- I -
i
I
AccountService.iava I!
---Same As Above--- 1 ' -
/
/r I
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 i
I
An I S 0 9001 : 2000 Certified Company \
-- _ _ _ _ 1
Page 9
-
-. -- - - -. -- -- --- - -- -- -- - ---- - --- - - - - ----
I Problem
I
Working with Hibernate 3.6, noticed the previous "org.hibernate.cfg.Annotat~onConf~gu~-at~on",
1s marked a s
"deprecated".
org.hibernate.cfg.AnnotationConfiguration;
i Solution
Q In Hibernate 3.6, "org.hibernate.cfg AnnotationConfigurat~on"is deprecated, and all its functiona!~tyhas been
! moved t o "org.hibernate.cfg.Conf~gurat~on".
I 4 SO, you can safely replace your "AnnotationConfiguration" with "Configuration1' class.
I Code s n i ~ ~ e...
ts
! /import org.hibernate.cfg.Configuration;
I...
private static SessionFactory buildSessionFactory() {
I try 1
return new Configuration().configure().buildSessionFactory();
1 } catch (Throwable ex) {
I
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionlnlnitializerError(ex);
1
I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An I S 0 9001 : 2000 Certified Company
Page 10
-- .- -- - - -- - - - _-- _ __ . ,,
Hibernate-CRUD
-.-
Application By Mr.SeltharRedciy
-- --- .--
- -- -.
___a 4
-
'
-- I
A
Account" />
. .
SessionUtil.java
1. package com.sekharit.hibernate.uti1; I
," -
' 2, import org.hibernate.Session;
3. import org.hibernate.cfg.AnnotationConfiguration; ,i .
4. public class SessionUtil { % .
I
5. I
,'
6. private static final ThreadLocal<Session> threadLocal = new ThreadLocaI<Session>();
7.
8.
private static org.hibernate.SessionFactory sessionFactory; ,I
9.
10.
static {
try {
I
:I
'
! 11. sessionFactory = new AnnoationConfiguration().configure(
: 12. "com/sekharit/hibernate/config/hibernate.cfg.xmI").buildSessionFactory(); -
-
15. }
I
1 16. } ,
I
\
1 17. ...........................
1 18. ........................... r
Account.iava
1. package com.sekharit.hibernate.bean;
2.
3. import-java.util.Date;
4.
5. import javax.persistence.Column;
I 6. import javax.persistence.Entity;
1 7. importjavax.persistence.ld;
I 8. importjavau.persistence.Table;
1 9. import javax.persistence.Tempora1;
' 10. import javax.persistence.TemporalType;
i1 11. @Entity
12. @Table(name="ACCOUIVT") .
1 13. public class Account {
1 14. private long accno;
15. private String name;
16. private double balance;
17. private Date creationDate;
1
18.
' 1 9 . @Id
20. @Column(name = "ACCNO", nullable =true, length=5)
21. public long getAccno() {
22. return accno;
,
I
Q.) Explain more about hibernate.cfg.xml (configuration file)?
I .
9 Hibernate slupports default connection pooling but which will not be used in projects We use always
1 server provided connection pooling.
I I) connection.pool-size: Used t o configure hibernate provided connection pooling in hibernate.cfg.xml :
I
I
I
2) show-sql: if the 'show-sql' value is true we can view all the hibernate generated queries in the
console.
I <property n a m e = " s h o w ~ s q l " ~ t r u e ~ / p r o p e r t y ~
I
-- 3) use-sql-comments : To add SQL comment t o the SQL query generated by Hibernate
I <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 ~
I
-
4) format-sql : Format the SQL ql;ery, so that easy t o read
1 <property name format-sqln>true</property>
-
I Case 2 : table exists
1 > 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. (Based o n HBlVl file)
I
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
-. - -- An IS0 9001 : 2000 Certified Company
------ -
Page1
I
3 If its value is 'update', hibernate will check for schema existence. If schema doesn't exist it will I
I
create the new schema. If the schema already exists it uses the existing schema for persistence
operations.
P Dialect class is a simple java class, which contains mapping betweerr java language data type and
database data type. i
--- - - -- 1-
Page 2
Hibernate-Arcl~itecturalElements
I I SAP DB 1 org.hibernate.dialect.SAPDBDialect 8
,
!
I
HypersonicSQL 1 org.hibernate.dialect.HSQLDialect
I I-
1 1
I I lngres org. hibernate.dialect.lngresDialect I
1 Progress org.hibernate.dialect.ProgressDialect
-1 I
Mckoi SQL I org.hibernate.dialect.MckoiDialect
I
I
I
I lnterbase org.hibernate.dialect.lnterbaseDialect 1 !
I
Pointbase
i org.hibernate.dialect.PointbaseDialect I
FrontBase org.hibernate.dialect.FrontbaseDialect
1/ Firebird org.hibernate.dialect.FirebirdDialect
..A
I
Q.) Explain m o r e a b o u t Hibernate mapping file?
I
> Each hibernate mapping file must contain only one <id> (or relevant t a g <composite-id>)
I > <id> tag property corresponding column can be primary key or non-primary key in t h e database
II
> In mapping file class names and property names are case sensitive. But Table names and column
!
names are n o t case sensitive. 1
I
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
!
-- PTe- 2-..
.-
, ~
~~ . - ~ ~ . .~ ~ . ~ ~ ' ,
j Hibernate-Archi tectul-a1
. . . . .-~
...
Elements -- Mr.SekharRecidy-La,D . - .
i - \
\
I
Ii P When the property name and column name both are same we no need t o give 'column' 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. But i t allows writing multiple objects -
mapping information within the same mapping file. Per each class mapping we need t o write one
<class> tag.
r Databases have different ways t o organize i t s tables. Some database places all tables in a different
I "schemas", some database places all tables in a different "catalogs". If we want we can specify this in
<class> tag of the mapping file
i 9 In mapping file we write fully qualified name of the entity class in "name" attribute of <class> tag.
Instead of that we can write package name separately using "package" attribute of <hibernate-
mapping> tag
P In the mapping file we no need t o map all t h e properties of the entity and all the columns of table. As
per our requirement we configure required properties of the entity and columns of the table
1 Q.) Explain about annotations which are used in our application t o m a p entity t o table?
I
I o @Column
---we----
8 _n
x
.&
Hibernate-AI-chitectural
lr... -~ ..
Elements
, ..I
~r.~ekl~ai-~ecldy
- -. -..
-
o @GeneratedValue
o @Temporal
/- All the above annotations we are taking from java.persistence package. Actually this paclcage is not
the part of hibernate API. This paclcage is from .IPA(Java Persistence API).
> These annotations also given by hibernate. But we don't prefer t o use hibernate given annotations.
We prefer t o use .lPA annotations. Reason for this is, Hibernate is a specific API, where as ]PA is a
specification.
If we use JPA annotations we have t o flexibility t o change the implementation vendor without
changing application code.
i > .IPA is an APl(from SUN), its not the implementation. There are multiple implementations are there
for ]PA. Some of famous implementation of ]PA are Open.lPA, Hibernate, Toplink Essentials, Eclipselinlc
...etc.
> Object Oriented representation of hibernate configuration file along w i t h mapping file is known as
-
Configuration object
-
1
3 By default Hibernate reads configuration file w i t h name "hibernate.cfg.xml" which is located in
"classes" folder
I
9 If we want t o change the file name or i f we want change the location of "hibernate.cfg.xml" then we
need t o pass user given configuration file name (along with path) t o "configure()" method of
1 Configuration class
1 P Configuration object Stores the configuration file data in different variables. Finally all these
variables are grouped and create one high level hibernate object called SessionFactory object.
I
P So Configuration object only meant for creating SessionFactory object
I
> If w e want w e can provide the configuration information programmatically, without writing
I configuration file.(But it will become Hard coding, so not advisable)
1 Programmatic configuration
I
Adding Entities(anrl0tated persistent classes) t o configuration object programmatically
,. ,
I Configuration cfg = new Configuration()
..
.addClass(org.hibernate.auction.ltem.class)
.addClass(org.hibernate.auction.Bid.class);
i
i
) To add hibernate properties t o Configuration object programn~atically
This is not the only way t o pass configuration properties t o Hibernate. Some alternative options include:
aSessionFactory I S created.
mappings.
- -- - - - - - - - - - - - - -- - - - - - - -
- -- - - -
Session is an interface and Sessionlmpl is implemented class, both are given in orghibernate.";
r Session object is called persistent manager for the hibernate application.
r It i s a single-threaded(not-thread safe), short-lived object
> It Wraps a JDBC connection
r The Hibernate Session operates using a single JDBC connection which can be injected by the
hibernate while constructing session object.
I
,
-
4.) What i s Transaction ?
-.
r Transaction used by the application t o specify atomic units of work (Transaction management).
- i Using Session Object we can create Transaction object in t w o ways.
o Transaction transaction =Session.getTransaction();
o Transaction transction = session.beginTransaction();
-1
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
. ..- ..- - .--.-- . . ...
....--..-. . - .. --. --
An IS0 9001 : 2000 Certified Company
-- --
Page 7
1 Hibernate-Architectural Elements . , Mr.Se1tharRecldy
-- -- --=A. s -
.mEC'
, C'scatc A
.-
i
Scssiorl Factor?.
TJses
I 1 DAI~I~:,SC
.. .1-:vL<cr\,c.i
-
. -
i'i.ypl.cation
3
'
1 ......
/I Session
- -
class
--
-.. ..... ................ --- ...................-.....-.........-... - --
.
I
!:
configure a database driver in eclipse:
> Launch o r open MyEclipse Database Explorer prospective. In the DB Browser window right click on
1 the white place and select "new " option. iL
/ O When w e choose t h e new option, it will launch database driver dialog box. Now we need t o fill t h e I
I following options in the dialog box. I
/ > Select driver template as oracle(thin driver), if we are using oracle database.
Give the driver name (logical name, which i s used t o refer this configuration) 1
I
1
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1
An I S 0 9001 : 2000 Certified Company J
Page 8
Hibernate-Architectural E l e i ~ ~ e i ~ t s
I
3 Give the connection url.
3 Give the username and password. I
> Click on Add Jars button, t h e n se!ect classes.jar file !
I
> select t h e java package and click on finish
I
Persistent Object life cycle
1 Persistent Object has three life cycle states
1. Transient state
! 2. Persistent state
I
I
3. Detached state
I (-"]new - -instance
.-.-
Transient State
: 'L- --A -- --
I Session.get()
I j Session.load() Session.save() ; Session.delete()
Session.iterate() Session.saveOrUpdate() i
! arb age collection
Session. uniqueResult() Sc.ssion.persist()
I
1i :
B Session.scroll() : Session.merge()
f
1.
1 I
1
: Session.evict() Session.update()
!i Session.saveOrUpdate()
i : Session.clear()
t Session.merge() ~arbage'collection
i : Session.close()
1 Session.lock()
I
!
j Session.replicate() ,,(. '
/.',.
i Detached State
;
,
:
/ Transient state NO
II Detached state
I
N0
I
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
.--- <,;_
-_
,-, 2;:
-.\ - ..-
,_.A,.. ,
..- r \
by------- --
/_/-
I - I ',., ------
--
-_--__--
!,2;/#; I...,.
,.,,-,.,, ::, I!.!,;I;,~~ I'~I.IcI(;I~
~ ! ? r a t .P
~ ~I~~
IT^^-^..
.--/ .
.%.,
,
/~,lill,~: a ~ ( c! l ~ , 2 ~ [ :$?::!,
i;~i:l~~;)
I i' 1 1 lrjl;
' - 1
l
. 31il.e~ ,1. 1 2 -.p:#:111r
,A
.
-:--tdL,.\
'-I
I
?PI'~~~IPI'I!
'-7r..'
I
7
from
-
4:ti:y.i'
Ada!:ltpd
4 . -----
"Hlt:~prr!atp iij ;
--_ -
I D~tached
/by IBallet' 4 G King ,I
I
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified Company
Page 2
1
I
I
I -
Hibernate-Persistent Object Lifecycle
..
--
I _
--
m _
..
_ < -
. w -
.. --
S
-.
~ .r . ~ e k h a -r-~ e d d T -
% ,.-
.
--,
Transient state: An object is said t o be in transient state, when i t is not associated with session and not present in
data base.
Example: Table
ACCOUNT
1 ACCNO / NAME / BALANCE 1
I
I
1 1001
1002 1 kesavareddy
Sekhar 2000
1500
1
i Application code:
1. Account account = new Account();
2. account.setAccountld(1003);
3. account.setName("yellareddy");
1 4. account.set8alance(l500);
> In the above example account object is not associated with session and there is no matching record in the
ACCOUNT table. So we can say that account object is in transient state.
,
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified -
Company
-- - --
Page 3 --
' H i b e r n a t e - ~ e r s i s t e lObiect
~t Lifecvcle
i
3 In this state object is non-transactional. 1.e. object is not synchronized w i t h record. 1.e. IVlodifications done t o
1
1 entity, doesn't save into database.
( Persistent state: An object is said t o be in persistence state, when it is associated w i t h session as well as object present
in database.
I
- ' Example: Table
i ACCOUNT
P In the above example account object is associated with session and there is a matching record in ACCOUNT
! table. So we car: say that account object is i n persistent state.
P I n this state object is transactional. 1.e. t h e object is synchronized with database record.
II
P Changes made t o objects i n a persistent state are automatically saved t o t h e database without invoking session
1 persistence methods
'
I
USE CASE: Explains Persistent state
Session session =SessionUtil.getSession();
1 session.getTransaction()begin();
1 Hibernate-Pel-sistei~tObiect Lifecvcle
- - -- -- - -
Mr.SekharReddv 1
/ Account account = new Accoui;t();
1
! //transition t o the 'persistent' state. Hibernate is N O W
1 // aware of the object and will save i t t o the database
I session.save(account);
I
/
USE CASE: Explains Transient state
Session session =SessionUtil.getSession();
sess~on.getTransaction().begin();
// notice the Java object is s t i l l alive, though deleted from the database.
// stays alive until developer sets t o null, or goes out of scope
I System.out.println(account.getBalance());
Detached state: An object is said t o be in detached state, when the object is not associated with session but present in
data base.
Example: Table
ACCOUNT
I ACCNO I N A M E I BALANCE 1
1001 1 kesavareddy / 15001
I 1002
I
. / Sekhar
I
2000 I
J
Application code :
1. Account account = new Account();
2. account.setAccountld(1004);
3. account.setName("cherry");
IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000
- .- -. -- -
Certified Company
-- - - - -.
- -- -
- -
Page 5
I
Hibernate-Persistent Object Lifecycle --
L"
Mr.Selt11arReddy
-- ~~-~~
-..----A -
4. account.setBalance(2100);
5. / / N o w the account object is said t o be in transient state
6. session.save(account);
7. // NOLVthe account object is said t o be in persistence state
. -,-
I Session
..... .......
..................
I
. .
... .. ...> __ ........
I i LOU2
lOUJ -
......
.. ..
',. .. ,
I => In the above example after callingsession.close() method, account object is moved t o Detached state from persistent
state. As session i s garbage collected, i f we try t o perform some modifications t o entity object those changes will not be
/ stored into database.
,-,
'
=> In this state object is non-transactional. Means object is not in sync with database. So Changes made to detached
objects are not saved t o the database. -,
I
i USE CASE: Explains D e t a c h e d state 1
I
,
/
//retrieve account w i t h i d 1. account is returned i n a 'persistent' state
Account accoilnt = session.get(Account.class, 1);
i // c o m m i t t h e transaction
session.getTransaction().commit();
1
/
USE CASE: Explains D e t a c h e d s t a t e
Session session1 =SessionUtil.getSession();
i
I
iI
// retrieve account w i t h i d 1.account is returned i n a 'persistent' state
Account account = sessionl.get(Account.class, 1);
// transition t o t h e 'detached'
Sessionl.close();
state. Hibernate no longer manages t h e object
I
I
// modification is ignored b y Hibernate since it is i n t h e
//'detached1 state, b u t t h e account still represents a r o w i n the database
/ account.setBalance(500);
11 // c o m m i t t h e transaction . "
I
j'
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
.-
An IS0 9001 : 2000 Certified Company
page-7-
-- -. -
. -.
~- . - . - - - .---
i
~
4 Each Session object contains one Persistentcontext. It might be containing t h e follow things:
I
' ~ l u s h i n tgh e Context
// 'transient'
state - Hibernate is NOT aware that it exists
Account account = new Account();
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
- An IS0 9001 : 2000 Certified Company
rage tr
--..- - - -. -- --- -
-. -
I H [be1nate-Session Methods Mr.SeltharReddv -
i Session m e t h o d s
I
I1 11.
12.
13.
private int accountld;
private String name;
private double balance;
i 14.
' 15. @Id
16. @Column(name = "ACCNO")
17. public int getAccountld() (
18. return accountld;
19. }
, 20.
public void setAccountld(int accountld) (
this.accountld = accountld;
i1 :
31.
public void setName(String name) {
this.name = name;
@Column(name = "BALANCE")
public double getBalance() {
return balance;
I
public void setBalance(double balance) (
this.balance = balance;
1
@Override
public String tostring() {
return "Account [accountld=" t accountld t ", name=" t name
t ", balance=" t balance t "I";
Hibernate Session provides two method t o access object e.g. session.get() and session.load(). 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.
- > As we can see the ObjectNotFoundException hierarchy, we can say this is un-checked exception.
.. .. So we no need t o
write try-catch block t o handle this exception.
-
/, 2) It is lazy loading, rrieans when we call session.load(Class, identifier) method i t will not return entity object, it will
return proxy object. When we try t o access the non-identifier properties from the proxy object, at that time it will hit
1
i the database and load the entity object.
i 3) As Session.load()return proxy instance, so it is not fully available in any future detached state.
I 2) It is early loading, Means when we call session.load(Class, identifier) method it will hit the database immediately and
i load entity object and return entity object.
I
3) As Session.get() returns a fully initialized instance, so i t is fully available in any future detached state.
I
, saves a database roundtrip if nothing other than creation of an association is done, w i t h the proxied instance in --
rnailaged state
NOTE: load() method exists prior t o get() method which is added o n user request.
.',
4.) HOW to call g e t and load methods ?
: 50. public void callload(){
51. Session session = SessionUtil.getSession();
j _
52. session.beginTransaction();
53. try { i
1 54. Account account = (Account) session.load(Account.class,9001);
1 55. / / ~ this
t line put Break.point ... Now observe the console, After this line executed, iI
'
!
56.
57.
58.
/ / w e can't find any select statement. And if observe on the variables window, account object not initialized.
// Now account is just a proxy object.
i
1 59. System.out.println(account.getName());
I
1
60.
61.
//After this line yo" can find select query on the console, And now account object is initialized with database data. 1
( . 62. } catch (ObjectNotFoundException e) { 1
// System.out.println(account.getName{));
//This would fail!!!
publicvoid callGet() {
Session session = SessionUtil.getSession();
session.beginTransaction0;
Account account = (Account) session.gct(Account.class,9001);
// At this line put ~ r e a.p'oint...
k Now observe the console, After this line executed,
/ / w e can find select statement. And if observe on the variables window,
//account object initialized with database data
// System.out.println(account.getName());
// no problem!!!
1. i f object present w e have t o implement some logic, if not w e need t o implement some other logic.
I get(): if the object is not there, it returns null. Then w e can implement above requirement as follows
I
if(object == null){
//some code
IL --
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
--
An IS0 9 0 0 1 : 2000 Certified Company
- --
Page 3
I
J-
~ ~
~p p~ - .... .-
I
//some other code I
load(): if the object is not there it throws an exception. So we can't implement this requirerne~itusing load()
For the above requirement we go for get() method.
2. If you we want t o use the JavaBean that you are retrieving from the database after the database transaction has been
conimitted, you'll want to use the get method, and quite frankly, that tends t o be most of the time. For example, if you
load a User instance in a Servlet, and you want t o pass that instance t o a Java Server Page for display purposes, you'd
need to use the get method, otherwise, you'd have a LazylnitializationException in your JSP.
3. get() method could suffer performance penalty if only identifier method like getld() is accessed. So consider using
load() method if your code doesn't access any method other than identifier or you are OK with lazy initialization of
object.
Persistent state?
Persistence state means the object is associated with session as well as presented in the database. If the object is in the
persistent state then the object is said t o be synchronized with database. 50 whatever modifications done t o the object,
,':
/ those changes will be updated i n the database and vice versa. So we no need t o call update() method when object is i n 1
I persistent state. I
' \
, Detached state?
I
I
Detached state means the object IS not assocrated with session b u t presented In t h e database In this state if we w a n t t o 1,
' d o any n~odificationst o the object w e should call update() method. Because in thls state the object is not synchron~zed
i w i t h database.
I
I public void saveOrUpdate(0biect object) throws HibernateException;
I
I
I If t h e record is n o t there i n the database ~t wrll try t o insert the record. If the record is there i n the database i t will t r y t o ,
! update the record.
1 Pseudo code o f saveorupdate():
1. class Sessionlmpl implements Session{
1 2. public void saveOrUpdate(0bject object){
i 3.
1 4. //SELECT THE RECORD
5. Object obj = session.get(object);
j t: / / I F RECORD EXIST
If( obj != null){
1, :: 10.
// UPDATE THE RECORD
updatejobj);
) else{ // IF RECORD NOT EXIST
11. // INSERT THE RECORD
I 12. save(obj);
13. /
Application code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
4. Account account = new Account();
5. account.setAccountld(1001); .
6. account.setName("sekhar");
7. account.setBalance(6800.00);
8.
9. session.saveOrUpdate(account);
10.
11. session.getTransaction().commit();
12.
13. //Now saveorupdate() internally calls save(), because record with 9001 i d is not available i n the database.
Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666, 23734842
l1
IS0 9 0 0 1 : 2000 Certified Company -
Page 5
~ .- -...-p---p-pp-.-..p..-- .
Hibernate-Session
. -
Methods ,. . -. -
-
--
Mr.SeltharRecidy
. .. . .
w
Table: ACCOUNT
I1 1001 6800
1
Application code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
i 4. Account account = new Account();
I 5. account.setAccountld(1001);
6. account.setNarne("selthar Reddy"); I
1 7. account.setBala1ice(8200.00);
8.
' 9. session.saveOrUpdate(accour~t);
10.
11. session.getTransaction().commit();
I 12.
!
i
i
13. //Now saveorupdate() internally class update(). Because the record with 9001 id i s already exists i n the database.
-
,I I
Table: ACCOUNT
i
I ACCNO / NAME I BALANCE )
1 1001 I rekhar Reddy 1 8200 1
I
! w i t h the session will be de-associated f r o m session and associated JDBC connection also closed. It is not strictly necessary to .
close the session but you must at least disconnect() it.
i
'I public void clear();
I
1 Table: ACCOUNT
1 Application code:
1. Session session = SessionUtil.getSession();
1 2 . session.getTransa~tion(/begin();
- 3.
4. Account accountl = (Account)session.get(Account.class,1001);
1 5. Account account2 = (A~~ount)session.get(Account.cla~~,1002~;
I
6. // Now accountl and account2 objects are in persistent state.
1 7.
8. accountl.setName("new sekhar");
1 9. account2.~etName("newkesavareddy");
10.
Hibernate-Session Methods -. ..
Mr.SekharReddy --::
I ---- -. , .
-.
!
1 11. session.clear(); I
I
!
12. //Now account1 and account2 objects are in detached state.
13.
-
!
/ 14. session.getTransaction().conimit();
~,
1
1. Session session = Sess~onUtil.getSession();
2. session.getTransaction().begin();
3.
4. Account accountl = (Account)session.get(Account.class,1001);
5. Account account2 = ~Account)session.get(Account.class,1002);
6. // Now accountl and account2 objects are in persistent state.
7.
8. session.clear();
9. //Now accountl and account2 objects are in detached state.
10.
11. accountl.setName("new sekhar");
12. account2.setName("new kesavareddy").
13.
14. session.getTransaction().commit();
A f t e r execution:
ACCOUNT
ACCNO BALANCE
sekhar
kesavareddy
I i i n the above example, when w e call session.clear() method, 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. i.e. account1 and account2 objects are moved f r o m persistent state t o detached state. I
I
9 N o w a c c o u n t l and account2 are in non-transactional state. So even w e are committing the transaction the modified
values o f account1 and account2 are n o t updated i n the database. i
I
iI Table:
ACCNO
ACCOUNT
BALANCE
I 1001 sekhar
1
I
1002
I
kesavareddy
I
9500 1
I
Application code:
1. Session session = SessionUtil.getSession(); r
i
I
1 1001
1002
I sekhar
1 n e w kesavareddy
1 8400
9500
'i In the above example when w e call session.evict(account1) a c c o u n t l object will be de-associated f r o m sesslon ,
I object.
- 9 After calling transaction.commit(), only account2 object will be updated. Because i t is in persistent state.
- !
1 public boolean contains(0bject obiect);
I
It is used t o check whether the object is associated with session or not. I
I I
I Application code: I
I
I 11.
12. session.clear();
13. System.out.println("After calling clear() method");
1
14.
15. if(session.contains(account)){
1
16. Systeni.out.println("account Is associated with session");
17. } else{
1
18. System.out.println("account is not associated with session");
- 19. }
I
i
public boolean isConnected(L
Page 8
.- .p..-p---p--.----... . . .. - .~.~-
~-
~
-.~
Hibernate-Session Methods Mr.Sel<hai-Reddy - .
1 Application code:
-
I
( 6. account.setBalance(9500); i
I
7. session.flush();
8.
9. System.out.pr~ntln("Breank..Point and observe the conscle..");
10.
11. session.getTransaction().commit(); I
I
3 In the above example when we call session.flush(), Hibernate checks or compares account object data and ,I
corresponding record database. If i t finds difference, it will execute update query t o update object data into the [
I
database record.
9 When transaction.commit() is called it will also check object data and corresponding record data. If it f ~ n d s I
I
different ~twill update object data into database.
9 So after transaction.commit(), we should not call sessioll.flush() because when we call transaction.cornrnit() I
session is in sync w ~ t hdatabase
, I
Batch Processing
9 The execution of series of programs is called batch processing. Batch processing is the process of read~ngdata i
--
I
from a persistent store, doing something with the data, and then storing the processed data in the persistent
1
store
9 Usually we run Batch process, when computer resources are less busy.
9 We are using flush() and clear() methods of the Session API for the batch insert process.
I When you need t o upload a large number of records into our database by using hibernate we are using the below code. !
~
1I ---.
s
-
~ a r e i Technologies,
-
- - -
--.,
i
Page 9
_
I _
Hi bel-nate-Session Methods Mr.SeltharReddy
. - --
1 Eg:
The prime step for using the batch processing feature is t o set hibernate.jdbc.batch-size as batch size t o a number
i either at 20 or 50 depending on object size. This shows the hibernate container t h a t every X rows t o be inserted as
batch.
I
Eg: -
-
I Table: ACCOUNT
I ACCNO BALANCE
I
sekhar
I Application code:
1 1. Session session = SessionUtil.getSession();
2. session.getTransaction(). begin();
3.
4. Account account = (Account) session.get(Account.class, 1001);
5. System.out.println("Before updating the database..."),
6. System.out.pr~ntln("Name: " + account.getNanie());
7. System.out.println("Balance : " + account.getBalance());
8.
,
9. // Break .point. go t o database and modify the data
10. ACCOUIVT
/ ACCNO ( NAME BALANCE 1
I
1 1001
I
1
1 Output:
Before updaticg the database ...
Name : sekhar
Balance : 8400.0
After ~ ~ p d a t i nthe
g database ...
Name : sekhar
Balance : 8400.0
1 Explanation:
> When w e call the get() o n session object, 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. And finally that entity object will be cached o n the
session object. I
When w e update the data o n the database i t will not get the updated data. Just it always shows session cached I
data.
, I
I CaseZ: w i t h single session, multiple times calling get() method:
Table: ACCOUNT
Application code:
1. Session session = SessionUtil.getSession();
2. session.getTransaction().begin();
3.
4. Account account = (Account) session.get(Account.class, 1001);
5. System.out.println("Before updating the database...");
8.
9. // Break..point ... go t o database and m o d ~ f ythe data
10. ACCOUNT
m] NAME 1 BALANCE 1
1
I
- Output:
I
I
Before updating the database ...
Name : sekhar
-1
Balance : 8400.0
After updating the database ...
I Name : sekhar
Balance : 8400.0
/ Explanation:
> When we call the get() on session object(second time), it will check whether the object is available in session or
not. If the object is available in session, it will not hit the database.
> In above example with Accno 1001 already account object i s already available i n session object. That's why even
we call get() method on session object 2ndtime, it will not hit the database. That's why it didn't display the
updated record data of database, instead it displayed previous data only.
8.
I
9. // Break ..point ... go t o database and modify the data
ACCOUNT
i Explanation:
i
! r In the above example, session2 object doesn't have any associated objects. That's why when we call get()
method on session2, i t hit the database and executes the select query and retrieve the record and display the
I
1
1 ACCNO ) NAME / BALANCE 1
I I I
I 1001 / sekhar 1 8400
I
1
Application code:
I
/ 1. Session session = SessionUtil.getSession();
v-
1 sekhar new 1 9500 I
9. session.refresh(account);
I
lo. System.out,println("After updating the database ...");
11. System.out.println("Name : " + account getName());
12. System.out.println("Balance : " + account getBalance0);
! Output: I
I Name : sekhar
I
' Explanation:
I > In the above example when we call refresh(), Hibernate compares database data and object data. If it finds any 1
- difference it will again execute select query and update the object data.
-
i public Obiect mergejobiect obiect) throws HibernateException;
Table: ACCOUNT
ACCNO NAME BALANCE
1001 sekhar 8400
Application Code:
1. session.getTransaction().begin();
2.
3. Account accountl=(Account)session.get(Account.class, 1001);
4.
5. Account account2= new Account();
6. account2.setAccountld(1001);
7. account2.setName("cherry");
8. account2.setBalance(6500);
9.
10. session.update(account2);
11.
12. session.getTransaction~).commit();
,1 Output: org.hibernate.NonUnique0bjectException: a different object with the same identifier value was already
associated with the session: [com.sekharit.hibernate.entity.Account#lOOl]
I
----
_-------- ---- .-
I:
/-
'-._
.311:
----..
: I CI I-A
--
r~t
.I :I -1 111
111 -1 ;I
-_--/-
.-I'
.->' -'-. --,,-
''------ :ze :% 15:1 1 1 1 rl .#:I
- ~t1:: .:I
.
I
---- -- --.-.
,/--
( IIIUI 2
13i:~ilL.~rlt2<-l ..:y <.--- --/--- 3:e :z:5.I13
i-1 -1-4 111114ate 1: 11
I '-------- - ---c- \
-
.
I
I
I I
i 9 We can't place two different objects(of same type) with the same identifier in the sesslon object.
> In the above example, by calling get() method account1 object with identifier '1001' will be there in session. And
i
by calling update() method account2 object with identifier '1001' is also trying t o come into session object. It is
I
In the above example, If we use merge() method instead of update() method, we won't get exception. Just
II 1
1
I
After execution: ACCOUNT
3 In the above example, when we call merge() method, first i t will try to load Account object with identifier 1002,
I As we don't have a record in ACCOUNT table with ACCNO#1002, it will insert Account(1002, cherry, 4500.00j
object into database.
Application Code:
1. Session session = SessionUtil.getSession();
2. session.getTransact~on().begin();
3.
4. Account account = new Account(),
5. account.setAccountld(1002);
6. account.setName("yeIlareddy");
7. account.setBalance(5600.00);
8.
9. session.merge(account);
10.
11. session.getTransaction().commit();
12.
13. session.close();
P
Sekhar
yellareddy 5600 i
In the above example, when we call merge() method, first i t will try t o load Account object with identifier 1002,
1 As we have a record in ACCOUNT table with ACCNO#1002, i t will try t o update with latest Account(1002,
- 1
I
yellareddy, 5600.00) object into database.
Case 3: merge() method merge the detached object data into persistent object
I
Table: ACCOUNT
-
---.--~--
'
I -
Hibernate-Session Methods
.
L
Mr.SekharReddy , :
.-
I
I
,-,
11 5.
1 6. Account account2= new Account(); -.
1 7. account2.setAccountld(1001);
i 8. account2.setNarne("kesavareddy"); . ~
9, account2.setBalance(6500);
i
I
,
I 10.
11. session.merge(account2];
12.
/--.
. .
i 13. session.getTransaction().commit();
j 14. session.close();
ACCNO BALANCE
yellareddy
I
I .-,
, In the above example, Before lltline;
h accountl is in Persistent state, and account2 in detached state.
I
-
. ,
/ > In the above example, when we call merge() method it will check, weather there i i any object associated with
the session with same identifier(1001). -
> In our example, accountl#1001 object is already associated with session, So merge() method now, Copy the <-
I
.
state o f accoun2#1001 object state into accountl#1001 object. After llth
line also, account1 is in Persistent ,
j
state, and account2 in detached state.
1 3 When the transaction is committed, As acountl#lOOl(Persistent-state) data is modified, so i t will hit the update
!
I
Application code: 1
II Account account = (Account)session.get(Account.class,1001);
Serializable id = session.getldentifier (account);
- Hi bernate-Sessio~~
Methods Mr.Sel<harRedcly
beginTransaction0 return different transaction objects. For each and every request transaction object creates a~lcl
This method is used t o move the object from detached state t o persistent state.
ReplicationMode has attributes described below.
P ReplicationMode.0VERWRITE : this mode reads the processing request and affect the result in database. After
committing the transaction the results are stored in database.
P ReplicationMode.lGN0RE : this mode ignores the processed request. ~ e a n ist doesn't affect the result in
datadase.
r ReplicationMode.LATEST-VERSION : this mode reads the processing request and affect the result in database.
P ReplicationMode.EXCEPTl0N : this mode reads the processing request and affect the result the database.
1 Application Code:
1. Session session = SessionUtil.getSession();
I ;: session.getTransaction(). begin();
session.replicate(account, ReplicationMode.LATEST-VERSIOIV);
Systern.out.println("After replicate() method");
i f (~ession.contains(account)){
System.out.println("associated");
} else {
System.out.println("not-associated");
II work is completed. So using lock(), i f we lock the record i t doesn't allow updating from different users till we commit the
transaction.
1 Hibernate defines Several lock modes
I
I
P LockMode.NONE : Don't go t o the database unless the object isn't in either cache.
3 LockMode.READ : Bypass both levels of cache, and perform a version check t o verify the object in memory is
I
!
the same version as that currently exits in the databse. 1
P LockMode.UPGRADE: Bypass both levels of cache, and perform a version check and obtain a database-level I
I
I
pessimistic loc upgrade lock, if that is supported. I
I
I P LockMode.UPGRADE-NOWAIT: same as UPGRADE , but use a SELECT .... FOR UPDATE NOWAIT on Oracle.
I
This disables waiting for concurrent lock releases, thus throwing a locking exception can't be obtained. I
-
9 LockMode.WRITE: Is obtained automatically when Hibernate has written t o a row in the current Transaction.
1
I This is an internal mode and can't bespecified explicitly.
I NOTE: this method got deprecated in Hibernate 4.x version I
I
Ih.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
An IS0 9001 : 2000 Certified Company
i
I -
pa e 1 F '
. ~ ~
- ~ ~ . A ~ ~ - . ~ - .
~
I OracleDataBase Table:
1
I
I SQL> desc account;
1 ACNO IVUMBER(5)
BAL NUMBER(8,2)
i
1 IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
An I S
-
0 9001 : 2000 Certified Company
Page
.- ~. .
,
~ ~
~ ~ ~
~~~
I ---
1 MySQLDat B e Table
-\
; +----.-. +- - - - -+----------- +
+-.-----.--
+----.- ---<- --+
I
I I Field I Type ( Null I Key ( Default I Extra (
I
Account.iava
1. package coin.neo.hibernate .VO;
2.
3 . public class Account (
*
4. prlvate- ~ n accno;
t
5. prlvate Strlng name;
6. privatedoublebalance;
7.
I 8.
9.
publlc int getAccno0 {
return accno;
j 10.
ll.
1
I
Naresh i Technologies, Opp. Satyam Theatre, ~ r n e e r ~ eHyderabad,
t, Ph: 040-23746666,23734842 1
An I S 0 9001 : 2000 Certified Company I-
Page 2
~..~.~...................................... . . --.
..--
By Mr. SekharReddy 7I
~~ ~
1. package com.neo.hibernate.dao;
2.
3 . import crg.hibernate.Session;
4 . lrilport org.hibernate. SessionFactory;
5 . import org.hibernate. cfg . C ~ n iguration;
f
6.
7. import com.neo.hibernate.util.Conn~ctionUti1;
8. import com.neo.hibernate.vo.Account;
9.
10. public class PracticeDao {
11. public static void main(String[] args) {
12.
13. Configuration configuration = new Configuration();
14. configuration.configure("com/neo/hibernate/config/hibernate.cfg.xml");
15. SessionFactcry factory = configuration.buildSessionFactory(j;
16. / / Oracle
17. Sesslon oracleSession =
18. factory.openSession(ConnectionUtil.getOracleConnecti~n());
19. Account oracleAccount = (Account)
20. oracleSession.get(Account.class, 1001);
21. System.out.println("0racle Account table details . . . . " ) ;
22. System.out.println("Accno : "+oracleAccount.getAccno());
23. System.out.println("Name : "+oracleAccount.getName());
24. System.out.println("Ba1ance : "+oracleAccount.getBalance()) ;
25. //Mysql
26. Session mysqlSession =
27. factory.openSession(ConnectionUtil.getMysqlConnection()) ;
28. Account mysqlAccount= (Account)mysqlSession.get(Account.class, 1001);
29. System.out.println("Mysq1 Account table details . . . . " ) ;
30. System.out.println("Accno : " - 1 - m y s q l A c c o u n t . g e t A c c n o ( )) ;
31. System.out.println ("Name : "+mysqlAccount.getName ( ) ) ;
32. System.out.println("Balance : "+mysqlAccount.getBalance());
33.
34. 1
35. )
36.
ConnectionUtil.iava
1. package com.neo.hibernate.ut11;
2.
3. import java . sql .Connection;
4. import java.sql.DriverManager;
5. lmport java.sql.SQLException;
6.
7. public class ConnectionUtil {
8. static {
9. try {
10. Class.forName("oracle.jdbc.driver.OracleDriver~');
11. Class.forName("com.mysql.jdbc.Driver");
12. 1 catch (Exception e) {
13. e.printStackTrace0;
14. 1
15.
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified Company
i
I
1-.
Page 3
.- ~~ ~ - ~- .
3.
4. <hibernate-mapping>
5. <class name= "com.neo.hiberi~ate.vo.Accountr'table= f'ACCOUNT">
6. <id name="accno" column="ACNO"></id>
7. <property name="name"></property>
8. <property name="balai?ceM column= "BAL"></property>
9. </class>
10. </hibernate-mapping>
hibernate.cfg.xml
1. <?xml version='l.Or encoding='UTF-6'?>
2 . <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Conflguratlon DTD
3.@ / / E N u
3. "http://hibernate.sourceforge.net/hibernate-configuration-3.O.dtd"> 1
4. <hibernate-configuration>
5. <session-factory> I
6. <property name="dialect">org.hibernate.dialect.OracleDialect</property> -
I
7. <mapping resource="com/neo/h~bernate/mapping/Account.hbm.xmlf' />
8. </session-factory> I
9. </hibernate-configuration>
I
I
~ r a c l e ~ a t a ~ Table:
ase
i
SQL> desc account; 1
Name Null? TY
i
1
ACNO NUMBER(5)
NAME VARCHAR2(10)
BA L NUMBER(8,2)
' Account.iava
PracticeDao.iava
1. package com.neo.hib?rnate.dao;
2 . import 0rg:hibernate. Sessj-on;
3. import com.neo.hibernate.util.SessionUti1;
4. import com.neo.hibernate.vo,Account;
5.
6 . public class PracticeDao {
7. public static void main(String [ I args) {
8. / / Oracle
9. Session oraclesession = SessionUtil.getOracleSession();
10. Account oracleAccount = (Account)oracleSession.get(Account.class,
11. 1001) ;
12. System.out.println("Oracle Account table details . . . . " ) ;
13. System.out.println ("Accno : "toracleAccount.getAccno ( ) ) ;
14. System.out.println("Name : "toracleAccount.getName());
15. System.out.println("Ba1ance : "toracle~ccount.getBalance());
16. //Mysql
17. Session mysqlSesslon = SessionUtil.getMysqlSession();
18. Account mysqlAccount= (Account)mysq1Session.get(Account.c1ass, 1001);
19. System.out.println("Mysq1 Account table details . . . . " ) ;
20. System.out.println("Accno : "tmysqlAccount.getAccno());
1
1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 1
I-.
An IS0 9001 : 2000 Certified Company
--- -- i
Page 6
.~.~ -- ~ -. ~ ~.. ~ ~ ~~ .~
I SessionUtil.java
- 1. package corr,.neo.hibernate. util;
2.
1 3. import 01-9. hibernate. S-ssion;
4. import org.hibernate.SessionFactory;
1 5. import org.hibernate. cfg . Configuration;
i
6. import org . ja:<en.Eunction . Conca tFunction;
1 7.
8. public class SessionUtil {
9.
1 10. private static SessionFactory oraclFactory;
11. private static SessionFactory mysqlFactory;
1
I
12. stacic (
13. n r ? c l Factory = new Configuration i : . ranf igure (
.
--
I ;: "com/neo/hibernate/config/~racle.hibernate.cfg.xml")
.buildSessionFactory();
' 1 16. mysqlFactory = new configuration() .configure(
, I 17. "corn/neo/hibernate/config/~nys~ql.
hibernate. cfg.xml")
- 18. .buildSessionFactory(!;
1 19. 1
20.
' 30.
31, !
1
1 Account.hbm.xrnl
1. <?xml version="l.0" encoding="UTF-8Ir?>
1 2. <!DOCTYPE hibernate-rnapplng PUBLIC "-//Hibernate/Hlbernate Mapping DTD 3.O//ENU
I "http://h~bernate.sourceforge.net/hibernate-mappng-3.0td" >
3.
4. <hibernate-mapping>
5. <class name= "corn.neo.hibernate.vo.Accoun t" table= "ACCOUNT">
-
I 6-
7.
<id name="accno" column="ACNO"></id>
<property narne="name"></property>
8. <property name= "balance" column="BAL1'></propert y>
1 9. </class>
10. </hibernate-mapping>
I
I I
I Naresh I l.echnolog~es,Opp. Satyam Theatre, Ameerpet, ~ ~ d e r a b a Ph:
d , 040-23746666, 23734842 I
I
An I S 0 9001 : 2000 Certified Company __I
I
Page 7
Hibernate-Multi Database Comn~unication Bv Mr. SeltharReddv :-
I
- ~
oracle.hibernate.cfa.xml
1. <?xml version= '1.0'encoding= 'UTF-8' ? >
2. <!DOCTYPE hibernate-configuration PUBLICu-//Hibernate/Hiberna~eConfiguration DTD
3. O / / E M V
3. "http://hibernate.scurceforqe.net/hibernate-co11figuration-3.O.dtd">
4. <hibernate-ccnfiguration>
5. <session-factory>
6. <property n-1ln~="dia1ect">crg.h~ibernate.dialect.Orac?e9Cialect</property>
i 7. <property name="cor1nection.url">jdbc:oracle.:thin:@localhcst:1521:XE</property>
.- -,.^- - .,<. ,,-. i3!ne11>S\,Stem.',/
--
8. ., .
.. . . . . . . . . :-.
. " ~ ' . . ' , " - L . , ! I - - .>.- ,,..I.;
. L
F:v.,..-....>-
'...,
' . ' - L .
i-:.'-.
. . P - . L '
14. </hibernate-configuration>
Naresh i Technologies, Opp. satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001 : 2000 Certified Company I -
page-g--.-
Hibernate-Generators using XML Mr.SekharReddy
I --- --- . .
--- -- -- .- - -.
-riWI
Generator classes
> Generator classes are used to generate the 'identifier' for a persistent object. i.e. While saving an object into the
I database, the generator Informs t o the hibernate that, how the prlrllaly key value for the new record is golng t o
generate
3 Hibernate using different primary key generator algorithms, for each algorithm internally a java class is there for its
1 implementatiorl
i' .
3 All Generator classes has to implement 'org.hibernate.id,ldentifierGeneratorU interface, And has t o override
i generate() metliod. The logic t o generate 'identifier' has to write in this method
I > In built-in ger\e~atorclasses, identifier generation logic has implemerited by using JDBC.
1 > If we want we can write the user defined generator class and it should implement
'org.hibernate.id.ldentifierGenerator' interface and has to override generate() method.
- > To configure generator class we can use <generator /> tag, which is ttie sub element of <id/> tag
-
I
> <generator/> tag has one attribute called "class" with which we can specify generator class-name.
i
9 While configuring <generator /> tag in mapping file, if we need t o pass anv parameters t o generator class then we
! can use <param /> tag, which i s the sub element of <generator/> tag,
1 Example: HEM
<hibernate-niapp~ng> 1
I <class .. > I
~
<Id .... >
1
I <generator class="generator-class-namet'> I
<param name="param-nameH>param-value</param> I
I </generator>
i
</rd> 1
I </class> I
I
I </hibernate-mapping> I
I
1 The following are the list of main generators we are using in the hibernate framework I
i
1 1. sequence
1 2. assigned
I 3. increment
I 5. seqhilo
7. native
8. uuid
1 9 guid
10. select
11. foregin
I
1 In the above generators list, are used for int,long,short types of primary keys, and uuid, guid are used when the pri~nary
'
I
> This generator class is database dependent i t means, we cannot use this generator class for all the database, we
should know whether the database supports sequence or not before we are working with it -
-.
P Not has the support with MySq!
-
I
~ P Here we write a sequence and it should be configured in HBM file and while persisting the object in the database ,
sequence is going t o generate the identifier and it will assign to the Id property of persistent object, Then it will store ' :
the persistent object into Database.
NOTE: MYSQL even won't allow to create SEQUENCE Object in that database. Then where is the question of calling that
f r o m hibernate applicat~on?
/
1
NOTE: When we configured generator class for an entity, then we no need t o assign identifier value t o entity object
I
whiie saving the entity. Even we assign the identifier value t o entity, it will not consider our assigned value, it will use !
/ generator class generated value as identifier value. It applies t o all generator classes.
I
1 Steps t o work with "sequence" Renerator
I
Step 1:Create a sequence
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
An I S 0 9001 : 2000 Certified Company I -
-.
Page 2
.-- .... ........ -- --- .. ..................... ....... -- - . . . . . . . .
Hibernate-Generators using X M. L
--. ---
Mr.SekharReddp ., - ,
! \ .
- . . . . . rims i
I
I (OR)
<id name=" accountld " column="ACCNO">
-
1 <generator class="sequenceU/>
</ld>
I
1 NOTE: If we don't configure any sequence name then i t will take default sequence name(HIl3ERNATE-SEQUENCE ). But 1
!I
I hibernate won't create the sequence, i f already sequence i s available with name "HIBERNATE-SEQUENCE", then it is !
'
used by hibernate. Otherwise hibernate raises the exception.
I
1 NOTE: But remember, if we enable hbrn2ddl.auto property in hibernate configuration file, then hibernate will create the
. .
1
- database objects i f they are not exist.
1I
I
NOTE: It i s not advisable t o use the default sequence, always prfer t o create a different sequence t o each enitity
I seperately.
I
1 Step 3: Create the entity and save it without assigning identifier.
i1
1. Session session = SessionUtil.getSession();
I 2 . session.getTransaction ( ) .begin ( ) ;
3.
1 4. Account account = new Account () ;
5. account. setName ("sekhar") ;
-
1 6. account. setBalance (5000);
7.
8. Serializable id = session.save (account);
I 9.
10. System.out.println (flAccount is created with accno : "+id) ;
( 11. session.getTransaction ( ) . commit ( ) ;
I
I Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, ~ ~ d e r a b a Ph:
d , 040-23746666, 23734842 I
I
An IS0 9001 : 2000 Certified Company
Page 3-
1
-- - -- -- - -- - --
IVOTE: When we execute the above code, we can find the sequence execution query on the console, which is used t o get
identifier for the saving enitity.
1 Internal Code
I
1 public void configure(. . .){
I sequenceName = PropertiesHelper.getString(SEQUENCE, params,
"hibernate-sequence"); // default sequence name
parameters = params.getProperty(PARAMETERS);
1
public Serializable generate(. . . ) {
Preparedstatement st =. . ..prepareSelectStatement(sql);
Resultset rs = st.executeQuery();
rs.next();
Serializable result = . . iterate results ...
return result;
1
1
I
NOTE: \\ow onwards for the following generator classes I just give the HBM configuration, you can u;e the same entity
saving logic(which we used in the above example as part of step-3) t o test them.
9 If generator class is assigned, then the programmer is responsible for assigning the identifier value t o entity before
saving into the database
I
1. HBM:
! Naresh i Technologies, Opp. Satyam 'Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An I S 0 9001 : 2000 Certified Company
I
1
,-
Page 4--'
--- ---- - ..~ ~ .- ~ ~ ~ . ... - - - .~ --I
-
I
Internal Code: I
I NOTE. Whrle testing don't asslgne ident~fiervalue to entity and then try t o save entity then ~tthrows
-
IdentifierGenerationException.
!
NOTE: While testing with assigned generator class, identifier type in enity should be some object type rather than iI
I primitive type.
!
I
'
> This generator supports in all the databases, so i t is database independent generator class.
I I This generator is used for generating the id value for the new record by using the formula
Max o f id value i n Database + 1
i
> If there is no record initially in the database, then for the first time this will saves primary key value as 1. 1
I i
. HBM:
1
I (OR)
<id name=" accountld " column="ACCNO">
I <generator class=" org.hibernate.id.lncrementGenerator " />
I
</id>
1 Internal Code:
-
I public class ~;@$@;@<~~tJj:$?~g.~$~~~$
;
:
+ -*!v-.5 *>.;,.: .;, ,x :, ~ :.,<,;:
I i f (sql!=null) {
getNext( session );
I 1
return ...fi nal number after adding '1'
,-I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An I S 0 9001 : 2000 Certified Company
...-. --.- --.... ...- . ..... .... . .. . .. --- -~ - .----. -
Pages-
~
~.- ~. .- -. . -..- --.-
-3
~ ~ ~
I The HiLo (High/Low) algor~thmknows how to generate unique number series using t w o values: the high and the low. I
-Ihe high value is used as a base for a series (or range) of numbers, while the size of this series is donated by the l o w
1I value. A unique series is generated using the following steps: 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,767. When I
the algorithm starts is loads the high value from the database and increments it in the same transaction (the new high I
value in the database is now 53). The range of the current numbers series can now be calculated:
1
I Lower bound = 52*32767 = 1,703,884
1
I Upper bounds = 1,703,884+32,767-1= 1,736,650
All o f the numbers in the range of 1,703,884 t o 1,736,650 can be safely allocated t o clients, once this keys pool has been
exhausted the algorithm needs t o access the database again t o allocate a new keys pool. This time the h i i h value is 53
1
(immediately incremented t o 54) and the keys range is:
I
Lower bound = 53*32,767 = 1,736,651
Upper bounds = 1,736,651+32,767-1 = 1,769,417
And so on
The big advantage of this algorithm is keys preallocation which can dramatically improve performame. Based on the low I
I
II-
1 IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
An IS0 9001
- : 2000 Certified Company _I-
I
Page 6
-- -- -- - -- --- - - -- .- -- -
- --- - -- -- -- -- -- ---
-
value we can control the database hit ratio. As illustrated using the 32,767 we hit the database only once in a 32,767
, ' generated keys. The downside (at least by some people - but in my opinion this is a none-issue) is that each time t h e
algorithm restarts it leaves a 'hole' in the keys sequence.
TableHiLoGenerator
A simple HiLo generator, uses a table t o store the HiLo high value. The generator accepts the following parameters
A table HiLogenerator which can store multiple key sets (multiple high values each for a different entity). This is useful
!
when we need each entity (or some of the entities) has its own keys range. It supportsthe following parameters:
I
The generator uses a single table t o store multiple high values (multiple series), when having multiple entities using the
I same generator Hibernate matches an entity t o a high value using the primary-key-value which is usually the entity
name. A sample table can look like
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
An IS0 9001 : 2000 Certified Company
Page 7
.~ .~ ............ .-.-pp--p----.---pp- ........... .....
A simple HiLo generator but instead o f a table uses a sequence as the high value provider.
I
!
Internal code
class TableHiLoGenerator extends TableGenerator {
I
I
1 class TableGenerator { i
I
public static final String COLUMN = "column";
i public static final String DEFAULT-COLUMN-NAME = "next-hi";
II
i public static final String TABLE = "table";
public static final String DEFAULT-TABLE-NAME = "hibernate-unique-key"; 1
3 It is just like hilo generator class, But hilo generator stores its high value in table, where as seqhilo generator
I
stors its high value i n sequence.
I
IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
L. An IS0 9001 : 2000 Certified Company I
Page 8
.-- --.--... . ~~ ~ -~~ .~ ~~ -.-~ ~~ ~ .. . . .
1
I
HBM:
-
<id name="accountld" column="ACNO">
<generator class="seqhilo" >
I <param n a m e = " s e q u e n c e " > ~ ~ ~ ~ ~ - S E Q < / p a r a m >
<param name="max-lo">S</param>
</generator>
</ld>
(OR)
I I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 !
An I S 0 9001 : 2000 Certified Company
:
I
p a g e 9 --
- .-..- - -- - -- - -- - - ---- ---- --
Hibernate-Generators using -
XML
--
- ~ i - . ~ e k h a r. ~ eI d d
'-
7.) native
I
3 native i s not having any generator class because, it uses internally identity or sequence or hilo generator
classes. I
P native picks up identity or sequence or hilo generator class depending upon the capabiliti2s of the underlying * I
database. I
-
H BM:
<id name="accountld" column="ACIVO">
IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 I
I
1 HBM:
- <id name="accountld" column="ACNO">
-
~ <generator class="uuid" >
</generator>
</id>
' I
select: select retrieves a primary key assigned by a database trigger by selecting the row by some unique key and I
foreign: foreign uses the identifier o f another associated object. Usually uses in conjunction with a <one-to-one>
I primary key association. I
1 Step 1:Take any java class and implement org.hibernate.id .IdentifierGenerator and override generate() method. In this 1
I I
method implement the identifier generation logic as per the requirement.
I
-
I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842
I
I
I
An IS0 9001 : 2000 Certified Company -.-
Page 11
I would try to update our site JavaEra.com everyday with various interesting
facts, scenarios and interview questions. Keep visiting regularly.....
Thanks and I wish all the readers all the best in the interviews.
www.JavaEra.com
A Perfect Place for All Java Resources