You are on page 1of 32

Hibernate by Example

Eitan Suez,
UptoData Inc
About the Speaker

Java Programmer

http://u2d.com/

eblog on http://!ava.net/

"#JS Speaker
$oal%

&o get you up and running 'ith


Hibernate

&o (earn )/* +apping 'ith Hibernate,


in a hand%-on, iterative manner

&o get a good, .ir%t-hand .eel o. thi%


.rame'ork
+otivation

+y experience u%ing Hibernate ha% convinced me


that it ha% many gem%, i% u%e.ul in many
circum%tance%, and i% 'orth %tudying

&he belie. that the be%t 'ay to learn %omething i% by


doing it actively
Style
/o 0

+odel a cla%% o. ob!ect%

1on%truct databa%e mapping

Export or update databa%e %chema

rite Hibernate code to %ave %ample data to


databa%e

rite Hibernate code to 2uery databa%e


3 until 'e4ve covered mo%t o. the mapping .eature% o.
Hibernate
/i%claimer

&here i% a lot to thi% .rame'ork, cannot cover every


a%pect in a %imple 5-2 hr cour%e

Empha%i% on con%tructing a meaning.ul %ample


application at the expen%e o. completene%%: 6 'ill
not be covering every minute detail o. the
.rame'ork
Agenda
5.Pro!ect 7ackground
2.+apping
8.&he AP6
9.Se%%ion :%age Strategie%
;.Per.ormance
<.7atch Proce%%ing
=.:%er&ype4%
>.Annotation%
?.&ool%, Hibernate 8 .eature%
hat i% Hibernate@

An )b!ect/*elational +apping A)/* +B AP6 .or Java

)pen Source A($P(B

&oday a part o. *edHat

Principal author: $avin Cing

)ther +a!or #igure: 1hri%tian 7auer

Almo%t a de.acto %tandard )/* + .or Java

1urrent ver%ion 8.5 A8.2 almo%t .inalB


)nce upon a time..
5. A %ingle mechani%m .or %peci.ying )b!ect-
/ataba%e +apping:

hibernate .hbm.xml mapping .ile%


2. )ne Speci.ic *untime AP6
Hibernate &oday

+ultiple Pro!ect%

1ompliance 'ith ne' EJ78


Per%i%tence Standard%

Support% both xml mapping


and Java ; Annotation%

Support% both the Hibernate


AP6 and the EJ78 Per%i%tence
AP6
5. +apping

&he proce%% o. %peci.ying the binding% bet'een an


ob!ect model and a databa%e %chema

Principal mechani%m i% via D+( mapping .ile%

Defacto .ile name exten%ion: i% .hbm.xml

+ultiple 'ay% to %et thi% up: a %ingle .ile, one .ile per
cla%%. 7e%t practice i% i% to u%e one .ile per cla%%,
'ith each .ile placed next to it% corre%ponding cla%%
.ile in the package hierarchy, and loaded a% a
re%ource
+apping

Entitie%

7a%ic Propertie%

1omponent%

A%%ociation%

+any-&o-)ne

)ne-&o-+any

+any-&o-+any

6nheritance +apping

+odeling 'ith 6nter.ace%


+odel-1entric

rite +odel 1la%%e% and +apping%E


$enerate /ataba%e Schema

*ever%e Engineering &ool% available to do the


rever%e
Coding a
Sample Application
(live)
The Model
&ype%: Entitie% v% Falue%

Analogou% to by-re.erence v% by-value %emantic% in


programming language%

Ju%t a% primitive% Aint4%B are pa%%ed by value a%


parameter% to method% Avalue% are copiedB, by-value
%emantic% in the databa%e implie% the %ame thing:
value 'ill map to a table column and 'ill not be
%hared or re.erenced by other entitie%

Entitie% on the other hand are the rever%e, they are


%hared Ae.g. a many to one %cenarioB
1omponent%

:%e .or giving by-value %emantic% to Java 1la%%e%

:%age highly encouraged

Principal mechani%m .or implementing a G#ine


$rainedH model Amore cla%%e% than table%B

:nlike entitie%, re.erence% are not %haredE rather


'holly-o'ned by parent entityE it% li.e-cycle i% bound
to it

1omponent% do not get their o'n table%: they map


to column% o. their parent4% table
+any-)ne

Example: 6nvoice re.erence% a %ingle


cu%tomer. )ther invoice% may
re.erence that %ame cu%tomer.

Example mapping:
<many-to-one name="customer"
column="customer_id" />
the column %peci.ication re.erence% the
.oreign key in the invoice table
)ne-+any

1hoo%e .rom among the variou% 1ollection


AP6 type% A(i%t, Set, +ap, etc..B

Hibernate al%o model% Bag Ano implied orderB


%emantic%, u%ing a java.util.Lit %ince the
collection AP6 doe% not provide a 7ag type
)ne-+any: laIy loading

/e.ault in hibernate v8

Hibernate implement% laIy loading by


providing it% o'n 1ollection AP6 inter.ace
implementation%.

&he%e implementation% don4t .etch record% .rom


the databa%e until explicitly a%ked .or A'ith a
li%t.getAiB .or exampleB

1on%e2uence: mu%t %peci.y 1ollection AP6


inter.ace% in your code Ai.e. u%e (i%t, not
Array(i%tE other'i%e 'ill get a
1la%%1a%tExceptionB
)ne-+any (continued)

Example:

key i% .oreign key in payment table

pmts i% li%t property name

key'ord bag i% one o. a number o. choice%, including


li%t, %et, map
<bag name="pmts">
<key column="invoice_id"/>
<one-to-many class="com.u2d.nfjs.Payment"/>
</bag>
+any-+any

+any-many a%%ociation% are %peci.ied


u%ing an exten%ion o. one-many.

Example:
<bag name="actors" table="Movie_Actor">
<key column="movies_id"/>
<many-to-many column="actors_id"
class="com.u2d.movielib.Actor"/>
</bag>
6nheritance

#our Strategie%:

&able per cla%% hierarchy

&able per %ubcla%%

&able per concrete cla%% u%ing union-


%ubcla%%

&able per concrete cla%% u%ing implicit


polymorphi%m
6mplicit Polymorphi%m

Per%onally a great .an o. implicit polymorphi%mE

6 .ind thi% mechani%m give% me the .reedom to


model u%ing inter.ace% 'ithout complicating or
%acri.icing per%i%tence

many-to-one a%%ociation% to polymorphic type%


%peci.ied in mapping .ile u%ing the JanyK tag

many-to-many a%%ociation% to polymorphic type%


%peci.ied in mapping .ile u%ing the Jmany-to-anyK
tag
2. &he AP6

7a%ic :%age

hat Spring )..er%

Luerie%

HL( AHibernate Luery (anguageB

1riteria AP6
7a%ic :%age
Primary &ype% are:

Se%%ion#actory

Se%%ion

Luery

1riteria
7a%ic :%age: Se%%ion#actory

)ne per databa%e

A .actory .or %e%%ion%

1ontainer .or JF+-level cache A%econd-


level cacheB
Prototypical Se%%ion#actory
1on.iguration
public class HBMUtil {
Configuration cfg; SessionFactory factory;

public HBMUtil()
{
cfg = new Configuration();
cfg.addClass(Customer.class);
cfg.addClass(Invoice.class);
// ...
cfg.setProperty(
Environment.CURRENT_SESSION_CONTEXT_CLASS,
"thread");

factory = cfg.buildSessionFactory();
}
...
Prototypical Se%%ion
6nteraction
Session s = factory.getCurrentSession();
s.beginTransaction();
// interact with session in this "pseudo" block
// for example:
Customer c = new Customer("Eitan");
c.setAccountNo(12345);
s.save(c);
s.getTransaction().commit();
hat Spring doe% .or Hibernate

6t re.actor% the u%e o. Hibernate

Avoiding duplication o. %e%%ion and tran%action


%etup and teardo'n code

Provide% variou% utility method% .or common


u%age%

Provide% t'o implementation%:

Hibernate&emplate / 1allback Pattern

Hibernate6nterceptor Aa Spring A)P


+ethod6nterceptorB
Spring .or Hibernate Example
getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session)
{
Customer c = new Customer("Eitan");
c.setAccountNo(12345);
s.save(c);
}
}
getHibernateTemplate().fetch("from Customer");
Po'er.ul Luery 1apabilitie%

HL(: &he Hibernate Luery (anguage

ob!ect-oriented

1riteria AP6

po'er.ul ob!ect model .or con%tructing and


executing 2uerie%

Luery by Example

"ot locked in: can per.orm SL(


2uerie%, including %tored procedure
invocation%
HL(

Po'er.ul ob!ect-ba%ed 2uery language

Hibernate tran%late% HL( to SL(

HL( %tatement% are %horter, more


readable than their SL( counterpart%
Prototypical :%e o. Luery AP6
String hql = "from Customer c where c.age > :age";
Query q = session.createQuery();
q.setInteger("age", 33);
q.setFirstResult(20);
q.setMaxResults(10); // fetch the third page
List customers = q.list(hql);
1riteria Luerie%

hat make% the 1riteria AP6 po'er.ul i%


that it allo'% 2uerie% to be %peci.ied by
compo%ition.

&hi% mean% that 2uerie% can be


con%tructed dynamically.
Prototypical :%e o. 1riteria AP6
Criteria c = session.createCriteria(Customer.class);
c.add( Restrictions.ilike("name", "Albert%") );
c.addOrder( Order.asc("age") );
c.setMaxResults(20);
c.list();
// entire sequence of calls can also be chained,
// like so:
session.createCriteria(Customer.class).
add( Restrictions.ilike("name", "Albert%") ).
addOrder( Order.asc("age") ).
setMaxResults(20).
list();
8. Se%%ion Strategie%

Se%%ion per re2ue%t 'ith detached ob!ect%

a ne' %e%%ion i% obtained .or every re2ue%t. any


ob!ect% needed in long conver%ation% mu%t be
attached to the ne' %e%%ion

)pen Se%%ion in Fie'

%e%%ion %cope i% extended to include vie' rendering


pha%e

Se%%ion per conver%ation

u%e %ame %e%%ion, but di%connect .rom underlying


J/71 connection a.ter committing a tran%action
Hibernate and the eb
Hibernate M eb

+o%t Java eb #rame'ork% provide a Servlet .ilter


that 'ill automatically %etup and teardo'n Hibernate
%e%%ion%

)ur code can %imply .etch the %e%%ion .rom the 'eb
%e%%ion or application context, and not 'orry about
having to clo%e the %e%%ion

Alternatively, %ince in +F1 all re2ue%t% go through


the %ame controller, you could put that code directly
in the controller %ervlet%. &hen all your action
cla%%e% are all %et to inter.ace 'ith a Hibernate
%e%%ion
Hibernate M eb
!"pen Seion in #ie$! Strategy may be
convenient .or en%uring that vie' template
AJSP et alB doe%n4t fault on laIy-loaded
a%%ociation% a.ter the %e%%ion ha% been
clo%ed
9. Per.ormance

(aIy #etching i% a double-edged %'ord

$ood to %top ca%cading .etche% ad in.initum

7ad i. have to per.orm multiple %elect% to get a


%ingle batch o. data .or corre%ponding to a %ingle
unit o. 'ork Amultiple trip% acro%% the net'orkB

:%ually dealt 'ith by %peci.ying de.ault .etch


%trategy a% laIy in mapping .ile%, 'hile
per.orming Eager Ano' named JoinB .etche% 'here
appropriate in the code, on a per u%e-ca%e ba%i%
"N5 Problem 6llu%tration
;. 7atch Proce%%ing

hen u%ing the Hibernate AP6 to in%ert many


record% into a databa%e table, the main
concern% are:

in%erted ob!ect% are not automatically pu%hed to


the databa%eE

Seion cache% the ob!ect%

*emedy i% %imply to periodically

pu%h the change% to the databa%e 'ith a call to


flu%(), and

clear the cache 'ith a call to clea&()


7atch Proce%%ing

Example:
Transaction tx = session.beginTransaction();
int i=0;
List<Widget> lotsOfWidgets = loadLotsOfWidgets();
for (Widget widget : lotsOfWidgets)
{
session.save(widget);
if ( ((i++) % 20) == 0)
{
s.flush();
s.clear();
}
}
session.getTransaction().commit();
<. :%er&ype

1an provide your o'n %erialiIation and


de%erialiIation mechani%m% .or propertie%
5.6mplement the Ue&'(pe inter.ace
2.Speci.y the property type in the mapping u%ing
typeOPcla%%nameP
8.Alternatively can create alia% .or cla%%name 'ith
Jtypede.K
:%er&ype Example: &imeSpan
..
<property name="timeSpan"
type="com.u2d.persist.type.TimeSpanUserType">
<column name="startDate"
index="Session_startDate_idx"/>
<column name="endDate"
index="Session_endDate_idx"/>
</property>
..
..
<typedef name="spantype"
class="com.u2d.persist.type.TimeSpanUserType" />
<property name="timeSpan" type="spantype">
..
Mapping File:
Alternatively..
:%er&ype Example: &imeSpan
public class TimeSpanUserType implements CompositeUserType
{
public Object nullSafeGet(java.sql.ResultSet rs, String[] names,
SessionImplementor session, Object owner) ..
{
Date from =
(Date) Hibernate.TIMESTAMP.nullSafeGet(rs, names[0]);
Date to = (Date) Hibernate.TIMESTAMP.nullSafeGet(rs, names[1]);
return new TimeSpan(from, to);
}
public void nullSafeSet(java.sql.PreparedStatement pstmt,
Object value, int index, SessionImplementor session)
{
TimeSpan span = (TimeSpan) value;
Hibernate.TIMESTAMP.nullSafeSet(pstmt, span.startDate(), index);
Hibernate.TIMESTAMP.nullSafeSet(pstmt, span.endDate(),
index + 1);
}
..
:%er&ype Example: &imeSpan
..
public static final int[] TYPES =
{ java.sql.Types.TIMESTAMP, java.sql.Types.TIMESTAMP };
public int[] sqlTypes() { return TYPES; }
public static String[] COLUMNNAMES = {"startDate", "endDate"};
public String[] getPropertyNames() {
return new String[] {"start", "end"};
}
public Type[] getPropertyTypes() {
return new Type[] { Hibernate.TIMESTAMP, Hibernate.TIMESTAMP };
}
public Object getPropertyValue(Object component, int property)
{
TimeSpan span = (TimeSpan) component;
if (property == 0) return span.startDate();
else return span.endDate();
}
public void setPropertyValue(Object component,
int property, Object value) {
..
}
..
=. Annotation%

An alternative inter.ace to the Hibernate 1ore .or


%peci.ying +apping

An alternative to u%ing xml mapping .ile%

1omplie% 'ith Annotation% Part o. EJ78 Per%i%tence


Speci.ication
Sample
Annotated
1la%%
Sample Annotated 1la%%
>. &ool%

Ant &ool%

//(-*elated: SchemaExport and Schema:pdate

Eclip%e Plug-in%

1on%ole: HL( %cratch pad

+apping Editor

Hibernate 1on.iguration #ile $enerator iIard

*ever%e Engineering iIard%

1u%tom Hibernate Eclip%e GPer%pectiveH


Some 6ntere%ting Fer%ion 8
#eature%

#ilter%

D+( Entity +ode


#ilter%

A %imple mechani%m to .ilter table%, %imilar to 'hat


vie'% provide, 'ithout having to %peci.y the .ilter in
2uerie%

#ilter can be de.ined and named in the mapping .ile

#ilter mu%t be enabled programmatically on a per-


%e%%ion ba%i% 'ith
session.enableFilter(filterName)
D+(//)+9J Entity +ode

A ne', Experimental #eature in Hibernate 8

Fery promi%ing, potentially enabling po'er.ul .eature%


including import/export, S)AP, and DS(&-ba%ed
reporting

1on%i%t% o.:

Adding D+( data binding in.ormation to mapping .ile%

&he ability to de.ine a %peci.ic entity mode to u%e 'hen 'orking


'ith a %e%%ion A.or D+(, u%e the /)+9J entity modeB

:%ing the %e%%ion AP6 to bind databa%e in.ormation directly to


D+(, bypa%%ing ob!ect model entirelyE bi-directional.
D+( Entity +ode

&o inter.ace 'ithHibernate in thi%


mode:
Session session =
HibernateUtil.getSessionFactory().openSession();
Session domsession =
session.getSession(EntityMode.DOM4J);
&he 1ode..
&he )utput
D+( +apping 6n.ormation
6ntere%ting )b%ervation%

+any )/* mapping %olution% have been devi%ed over


the year%. Hibernate i% probably the mo%t
%ucce%%.ul.

E..ectively addre%%e% ma!or ob!ect mapping


problem% head-on, giving u% choice% .or modeling
inheritance, polymorphi%m

#lexible .rame'ork, can provide o'n


implementation% .or %erialiIing propertie%
A:%er&ypeB, ho' propertie% are acce%%ed
APropertyAcce%%orB, and more
1onclu%ion%

Hibernate i% a mature, complete %olution .or


addre%%ing )b!ect/*elational mapping

6t i% an active pro!ect 'ith a large community, large-


%cale adoption, keep% up 'ith Aand ha% a%%i%ted in
rede.iningB Java Per%i%tence Standard% and evolution

(ot% o. tool%: D/oclet / Ant / Eclip%e &ooling


*e.erence%

http://'''.hibernate.org/

)i*e&nate In Action A7auer M CingB

)i*e&nate, a Develope&+ ,ote*oo- AElliottB

)i*e&nate .uic-l( APeak M HeudeckerB

)i*e&nate A6ver%onB
1ontact 6n.ormation

Eitan SueI

http://u2d.com/

email: eitanQu2d.com

You might also like