Vous êtes sur la page 1sur 176

C

p o g a ficem&$.z~,xa
.,...,:,,..: .
m o b 40,g
~ ( g ~ J)
~ e~g$ u s y ? u e ~pus
. 3 (q~~es~g);~rmn)lbipn ; s u o g e l n ~ e ~ 8 u o a
.

. .
. . .
. .
.
. . .... .

k
h

. .

l/~m
nofi
* p mn o f i i & . a..#:~
;cI..:~
,... @ j a q .
u:aym amp b aw03
LL

c,,.~Li:i,i.,.

....:.:

s f i v m,.-~i,,..<>&!>?,'
a*...; ~ p m . a ~uaaya~nofi a u o f i u ~

4 nofi
~ aucpfiun
~
~ ':w3nofi
3.
.<:?

fiu!qjfij~na
mvaT99

' Iibel-nate is built on top of Jdbc.


,

;I bernate

not only takes care of the mappings from java classes to


..:::base tables but also providesdata query and retrival facilities and
::xisignificantly reduce development time otherwise spent with
:nanualdata handling SQL and JDBC.
i irbemate's goal is to relievethe developer Gom 95% of common data
;msistencerelated programming tasks.
:! j ;.,
:i;;ernate is used to.Persistance .theobject state in the persistence
!.r~edia
like database.
iii order to store state of an object in the:;relational database ORM is
plain Jdbc.
!jetter., .than
.
:libemate is a solution for ORM (Object Relational Mapping System).
.!t refirs to the technique of mappinga data fiom.an object model with
S Q based
~
commands.
~ r a m Gorks
e
which are using ORM technique likeTopLinks, IBatis,
:-libemateand Ejb EntityBean, in order to store the state of ?bject.
.--,.
.kjb EntityBian can not be used in non-ejb applications. Themain
..
..
..::::.
..._.
. . ..
. ..-...,. ,... .
limitation of thisis performance.
.f
.. y
..-:.:.:.
e use JDBC: then we;want
to.hard-.~.qde
the sql queries insid&he
.
.
. .
'.. --..
,f@z:file. If we use ~ i b & ~ & ~ , iwe
& &fi7t
&
require to hardcod; the
.! ., . .
?QL,
;queries
; .; in our Java program. : : : : ;
SQL
4ukrjes will automatically gene&tid>by:~ibt$-nate
depending on
.
then
;:r database. S o whdnever we are going to changethe;.database
.. .
l l v g file is.&ot required to modify. ~ u schanging
t
theG~,~.?ddriver
.::;z~ssin the configuration file is enough. Then hibernate will generate
... i. ::.ri~.!eries
.,. .
automatically based on database.
::;<
.;:.;!
: : x-u,uwy. e using.straightaway Jdbc in java:program then achieving
'r~,&sa@i'bn
.
~ana~em
.. .. eand
n t Cache Management are very.di!fficult.
. ,.:!
'.nd al$d'ri&d
=
.*,,
to -te s o r e.code
. and interac$Gn;ae:yev:Id;&~vlt.
. ..
;.$c..5%~.
,...=::
; :,,ibernat&i&'haVing
s o ~.&e&hds.
s. . ..ii.::-..
to interact wif&@at:&2se (Those
-l:relhodscai in&&ct with d&abL$e
.. . though Jdbc only) and also very
-::,A. :nethod call's wehave to keepin ydur java progrzm.
j ~ . ~ +file
> awill be independent of sql queries or database.
'

j.,

L-i

,
:
I

>.

.:

<:

,.

,.;

YZ1:..r.

., .

..

-$.$

x,

+\:

..&.:

. .?. .,:.App
\.
S1
"l

Hibernate

Jd bc

DB

Here Java file sending a action to hibernate but not sql queries.
Based on the;action (i.e insert or update or select) hibernate will
generate sql query and sends to the database.
If you hiive&equirement of using some'datavery frequently, instead of
readingifiom database every time, read once and keep in the cache and
then 2-??time onwards read from the cache, it reduces number of
.
.
network.calls.
If you are using Hibernate, you can change the databgeone to another
.development
itself.
at the time 6%
.
..
For exampleatthe time of development you used mysql aft;;.
production your client/customer wants to change database to Oracle
thgn;ho need to do%chang&i
in yourjava code. You need to do changes
. .
in:th+&nfiguration
..
.-.
:very
.
successfully.
..
file and:can execute
.
Hibe&$ti$id typically used in ~ a v ~ .. ~ w i ~ ~ ~ . aJava
~ ~Servlet
~ a t i o.; n s ,
applicat?ori$,:orJ2ee applications using session-beans.
Hibernate supports "Transactions"
(~ransaction.;means
making
multiple units,& a single bundle i.e a transaction can contains insert,
one query fails to execute then remaining also
update, delete,iif. .. . any
.
.
....
willcnot
._ .. . .execute$
;
:-.-.,;.:
._ .. .- -......
,~.
.*.. .
We >d.$k:.achie~s~
?
.mapping
through
Hibe&ie!,very
easely.
$<:
:
,...
+>.:
..
, :..
_. . .,
.:?< :::-.
. ...
By H i E e m>,.a t e ~ &
can achieve where conditi(jn$ !very simp]e f:.(i
:$
.
By Hibernate-managing joins is very easy.
Hibernate is developed in java so, it is platform independent.by this we
can achieve pure object oriented (database ioteractions also).
Hibernate can be used for any kind of java application that can be
standalone, web-application, or enterprise application in where.the
database interaction is required.
Hibernate uses Object oriented querying language.
Hibernate is free tc use no need to buy any licences. It is also a
opensource, we can download the source code and can enhance.
Usage of Hibernate is nothing but using sessipn object effectively.
Hibernate maintains two level cache.
.

.
,.,
. ,..
.
.

_ > . .

'

..

.; ....

.. ." . .. .

, ..

'

.:

.,

,...
. . :>.>.

...;,..

:: :..;

,-

.
.

.." . '

"

.,,; .-.:. <:,.:

Lara Technologies

... ... .

080-41310124

A major portion of the develoument of an enterprise application


involves the creation and maintenance of the persistence layer used to
store and retrieve objects from the datzibese of choice.
If changes are made to the underIying database schema, it can be
expensive to propagate those changes to the rest of the application.
Hibernate steps into fill this gap, providing an easy to use and powerfull
object relational persistence fi-ameworkfor java applications.
Hibernate provides support for collections and object relations, as well
as composite types. Userdefined data types and composite primary keys
give additional flexibility to support legacy applications.

Hibernate
-

key features:

Natural programming model: Hibernate supports natural 00 idiom,


inheritance, polymorphism, composition and the java collection
framework.
Support for ultra-fine-grained object models: a rich variety of
mappings for collections and dependent objects.
No build-time bytecode enhancement: there is no extra code
genaration or bytecode processing steps in your build procedure.
Extra scalability: Hibernate is extremely perfomant has dual-layer
cache architecture, and may be used in a cluster.
The query 'language: Hibernate addresses both sides of the problem;
not only how to get objects into the datzbase, but also how to get them
<ut again. ' '
Support for application transactions: Hibernate supports both longlived persistance contexts and detachlresearcn and takes care of
optimistic locking automatically.
Freelopensource: Hibernate is lisensed under the LGPL (Lesser
GNU Public Lisesce).
, :
Ejb3.0: Hibernate implements the persistance API and quarey
lailguage defined by EJB3.0 persistence, two members of the
1-J;ibernateteam are active in i'ne expert group. Ii provides t h e e hfifeatured query facilities those are 'Hibernate Query Language'.
'Hibernate Criteria Queiy7, 'dialect of the database'.
Hibernate is scalable: Hibernate is very perfoment and due to its
dual-layer architecture can be used in the clustered envir~nment.

Lara Technologies

Less rlcve!opment time: Hibernate reduces the development timings


a s i t supports inheritance, polymorphism, composition and the java
collection framework.
Automatic key genera tion: Hibernate supports the automatic
generation of primary key.
Enhanced Criteria query MI: with full support for
projectionfaggregation and subselects.
EJB3-Stylepersistance operation: defines the create () and merge ()
operations-which are slightly different to Hibernate's saveorupdate ()
and saveorupdatecopy () operations. Hi bernate3 will support all four
operations as methods of the session interface.
Hibernate X M L binding enables data to be represented as XML and
POJOs interchangeabily,
The EJB3 draft specification support for POJO pers-istanceand
---. annotations.
lmoernare Based kppiication Architecture:

Persistant Objects

..

-.

.-.
.
.

ExIl
Configuration

Transaction

To use Hibernate, it is required to create a java class that represents the table
in the database and then map the instance variable in the class with the
c o l ~ m n in
s the daiabase. Then Hibernate can be used to perform operations
on the database like select, insert, update and-delete the records in the table.
Hibernate architecture has three main components:
1 . connection Management:
2. transaction Management:
3. object Relational Management:

Hibemate provides a,lot of flexibility in use. It is called 'lite' architecture


when we only use the object relational mapping component. w i l e in 'full
cream7 architecture all the three component Objects Relaational Mappings
are used.

Hibematre is being used with other configuration management aqd


transaction management tools. For example apache DBCP is u s e d , f< ~- r
conneptioq
puuiiiig ~iLLiitile Hibernate.
..
9

Pre requisits-to use hibernate:


1. Any one of the database.
2. For that database 4" type of driver jar file.
3.- Java ~ e v e l o ~ m eKit
n t of J2SE.
4. 1f you are using:web-application then only any one of the webserver.
I,

The officik-website for hibernate is 'www.hibernate.org7.


In order to interact with database by using Hibernate need to update
classpath or buildpath with relavent jar files.

lnorder to use hibernate framework we should ~ p d a t eclasspath or


buildpath with the relavent and dependent JAR files those are: 1. hibernate-3.2.jar file
2. Driver JAR file
3. dependent JAR files which are inside lib folder of hibernate-3.jar

Hibernate API
Session (orp.hibernate.Session):
Session object is similar to the HttpSession 0bject.s A single-threaded,
short-lived object representing a conversation between the application and
the persistent store. Wraps a JDBC connection. Factory for T r a n s a c t i o n .
Holds a mandatory (first-1evel)cache of persistent objects, used when
navigating the object graph or looking up objects by identifier.
SessionFactory (or~.hibernate.SessionFactorv):

SessionFactory is a singletone object for entire application there will be one


sessinfactory object. A single-threaded, short-lived object representing a
conversation between the application and the persistent store. Wraps a JDBC
connection. Factory for T r a n s a c t i o n . Holds a mandatory (first-level)
cache of persistent objects, used when navigating the object graph or looking
up objects by identifier.
Configuration (or~.hibernate.cf~.Confipuration):
.

.. .,
.

..

In order to complete
.
configurationi::df&&offi%hibernate
we use this class.
. . .
.;
..

. .

:.

. ,

.. ..

> .

...

'

Query(org.hibednate.cf~.quew):
In order to c o n s t f u c t ' queries
~ ~ ~ we use this interface. Not .only this
interface we can a1s.o use Criteria interface.

Transaction (org.hibernate.Transaction):

(Optional) A single-threaded, short-lived object used by the


apclication to speciijr atomic units of work. Abstracts application
from underlying JDBC, JTA or CORBA transaction. A Session might
span several Transactions in some cases. However, transaction
demarcation, either using the underlying API or Transaction, is never
optional!
With hibernate API jdbc get the hql queries and it interact with the Jdbc and
it will convert the hql queries in to the0sqlqueries to interact with the
database.

Lara Technologies

Getting Start with Hibernate:


Hibernate is free to use and it is opensource .
There is a website to do\mload (lvww.hibernate.01-c). At the time of
downloading we will get one zip file i.e hiberna te-3.2.3.ga.zip.
Unzip it to the favourable location. Inside unzipped folder you can
find many folders. Among them hibernate3.jar (i.e core hibernate)
and jar files in the lib (hibernate dependence .jar files) are required to
develop any hibernate related application.
Take both jar files and update classpath or buildpath (in eclipse) or
copy into lib folder of web application.
Development steps for Application proiect:
For Every framework there will be one configuration file Eg: for struts
struts-config.xm1. Like wise for hibernate also there is one config file i.e
hi berna te.config.xm1
First develop one hibelxa:~.config.~'~:i
fcr ynvr r~pp!iclticnwder
classpath. Inside this xml file we have to explian about.
I. DriverClassName.
2. 'Lm.
3 . Usemame to connect to database;
,4. Password to connect to database.
5. Type of 2ndlevel cache.
6. Dialect class. Through this we are updating database
type (Dialect means pronouncing same language in
different accents).
,

...

. . . . . :,

Develop "POJO
. ..class"(Pl~iq@ld~Java
.
:...
Object). It is similar to
:;;A .!. :
usebean or forrri bean.
For every pojo cl&&develop one hbm (hibernate mapping) file.
Update ~onfi~uration'file
with hbm file path.
Write client program .Inside this, we have to f ~ l l o wfollowing steps.
I. Open hibernate. session.
2. Start transacfio~n:
3. Use transaction::... .
4. Commit transaction
5. Close the session
.

.!..

':

"..

.: .:

Lara Technoiogies

'

'

Developing core iava related proiect:


Developing a simple helloworld stand alone application by using
mj-Sql database.

Go to scljpse and create one core java related project.


Now update the buildpath with hibernate3.jar (i.e core hibernate) ,
jar files from lib(hibemate dependence .jar files) and the Driver jar
file.

I.

2.

Now develop hiberna te.cfg.xml file inside src folder

3.

<?xml version=' 1-0' encoding='utf-8'?>


<!DOCTYPE hibemate-configuration PUBLIC
.//u;L~-,.+.
,laLc,lTibelmate Configuration DTD 3.0//ENn
"http://hi bemate.sourcefor~e.net/hibernate-configuration-3
.O.dtd1'>
11-

..wbi

<!-- Database connection settings -->

<property name="connection.driver classw>


c0m.m ysql . j d b c . ~ ~ i v e r < / ~ r o ~ e r t ~ >
<property name="connectj o;l.urll'>
jdbc:mysql ://localhost/larac/property>
<property narne="connection.usernarne">root</property>
<property name="connection.password''></property>
<I--SDBC co~lnectlonpoo! fuse the built-in) -->
<property r?ame="connection.pool -sizeu>l </property>
<!-- SQL dialect -->

<property narne="dialectfl>
org.hibemate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's auiornatic session context management -->

<-propefi;.; name="curi-ent-sessio~l
-context-class">thread</property>

L s r a 'I'echi~ologies

080-4131 0124

<!-- Disable the second-level cache -->

<property name="cache.provider-classw>
org-hibemate.cache.NoCacheProvider</prope~>
.

<!-- Echo all executed SQL to stdout -->


<property name="show-sqll'>true</property>
<!-- Drop and rc-create the database schema on startup -->

<property narne="hbm2ddl.auto">create</property>

.
..

.
-,

. .. .
.. . ;,'; . ::

NOW
create a package.structureand develop a Pojo object.
.
.......
.:

...

.:.

,..' ,;:

. . ' . . .

V@:.xyapt to crate table f i r . ~ . e r s bwith


n column names as
(Person-~D,PERSON-NAME, PERSON:. , A G E..).'>:,,:,s.......
~
. &develop
~~
one P
/.
. . . . .. .. .. .. . . .
:-:class with all f$se,,attributes
.

.
...

.<

. .. .

... :

package corn-lara;
pu.bIic c1ass;Person
.
{: :I.:
.
.
;;.
:::,:~private..l~teger
.
id;
..p<i.vateString personName;
private integer p e r s o d g e ;
.

:.:

'

...

''

. .

public int:getId () (
ret',,;* id;

;
. . . . . . .,

..; .

public void setld (int id) {


this.id = id;.

. -.
.

. . .. .
....

public String getPersonName () (


return personName;

public void setPersonName (String personName) {


Sara Techi;ologies

080,41310124

II

this.personNamz = person~ame;

pu blic in t getPersonAge () (
return personAge;

>

public void setPersonAge (in t personAge) (


t h is-personAge= personAge;
>

>

5. Now develop one hbm file for every Pojo classinone. package.
.

"..: ..

- ally
In hibernate with out primary key we can't develo;::':
. . .

>.

.----

L-B-1-

tLaiJlG.

In h brn file we:want to take care about all attributes fo&ce,&ing


. . .[-. table.
In persons table we want to make PERSON-ID columnas' -'i.:$i:$'::,
.. ...
.
autoincrement and primirykey then use id and generator'iag~.i
iCZ

,;

<?xml version=" 1.OM?>


<!I?OCTYPE hibemate-mapping PUBLIC
"-//Hibeinate/Hibemate Mapping DTD 3.O//ENW
"http://hi bernate.sourceforge.net/hibernate-mapping-3.O~dtd">

6. Now develop one client programm


Lara Technologies

080-41310124

2.

.?.

htt~:i!javrteasytosi!~c(?m

package corn-lara;
import org.hibemate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Manager {
public staiic void main (String [] args)

person pl = new Person 0;


p l .setPersonName ("RAMESH");
p 1 .setPersonAge (29);
N 1. Configuration
Configuration config = new Configuration ();
config-configure ();
- - ---:-TT'L. ---..4,.
//2. Op--ell AL
LUG 3GSSiu~ix i I u - s

x i s a i i

SessionFactory sf = config.bui1dSessionFactory 0;
Session session = sf.openSession 0;
//3. Start the Transaction
session.beginTransaction 0;

5//4.'Use the Transaction


sessi'on.save (p 1 );
115. Commit the transaction

se~sion.~et.~ransaction
().cornmil ();
116. Close the sessiorr
session-flush ();

session.close

0;

I
7. Now start the database (i.e MySql4) and run the program.

Eara Technologies

Updating the record in the database tirouih Hibernate:

Developing a simple helloworldstand alone application by using


-MySql database.

1. Go to eclipse and create one core java related project.


2. Now update the buildpath with hibernate3.jar (i.e core hibernate),
jar fiIes from lib(hibernate dependence .jar files) and the Driver jar
file.
-. .

3. N o w develop hibernate.cfg.xm1 file inside src folder

<?xmI version=' 1.0' encoding='utf-8'?>


<!DOCTYPE hibernate-configuration PUBLIC
"-/Hibernate/Hibemate Configuration DTD 3.0//ENH
"httpri~%ibemate.sourcefor~e.net/hibemate-configuration-3.O.dtd">

<session-factoiy>
<!-- Database connection settings -->
<property name="connection.driver~class">

corn.mysql.jdbc.Driver</property
<property naine="connection.url">
jdbc:mysq1:l/localhost/lara</property>
<property name="co~mection.username">rootc/property>
<property name="connection.password"></property>
<1-- JDBC connection pooi (use the buiit-in) -->

<F:cpei-ty i;ame="comection.pool-sizen>l </property>


<I--SQL dialect -->

<property name="dialectN>
org.hibef~ate.dialect.MySQLDialect</propert~>
<!-- Enable Hibernate's automatic session'context management -->

<pmperty name="cu~rent
-session-context-class">thread</property>
<!-- Disable the second-level cache -->

<property name="cache.provider-classn>
org .hibemate.cache.~o~ache~rovide~lproperty~
<!-- Echo all executed SQL to;~dout.-;>
- ..
<property n a m e = " s h o w
. .s q
. 1,~~~e</pr6pe~>
, ,

. .. .

.:* . . . ...

'. .
:

<!-- Drop and re-createj..thedatabase'schema on startup -->


<property name="hb~~~~d1.autd~~~uPdate<lproperty
.
:

. . .

. . . . .. .

<mapping resource="com/lara/Person.hbm.xml'l~
. .

</session-factory>

4.

.: '

Now create a package structure and develop a Pojo object.


.,

...
:

.. . . ..
. -. ..

. :,.. ,

.,:'.'

A:.,

. i...

::

/'

- - We want to crate$fablefor,
with column names as
<*-: person
. . .
(reis&:-ID, PERSON;
-N .-m. .....
: .,P,?. E.:.. .m O N AGE).So
first develop one.Pojo,:
. .
class . . . . these attrjbufes-$.~~'<.-i
?:,.F; : $;.: :.:-:
.

...

..

'

.:

,.>.

"

-.: .- ' .

....

..

. ..

.- .,.. .
.

. .. . . , ;7,;. .
. . . .
?.,!(%
. .. . <..,
. .. .

..

.,

.. .. .. . .

.. .
. . ... . :

..,

'

. .,

.
,
%
.
:

:.

.. >

..

.....
. -

:.

..

:.

: , . . a >..

.. . .

.... : .

.:..:..

pa~kage'com~lara;
public claisPkrson
. . .
..

..:...;;=::*. .

j F:
%>,

private;qt
. . . . _ . . . id;
: iprivate<s.txin,g
. +.?:.? :..;.
personNarne;
.......:..
...A . : . . . . .
f;pA'ilva
. . .
teintiperson~ge;
. . . . . . . <..
.. . ;:,
,

. . .

.$. :!-i;

. .

:,

. . . . .
:

.Z.?&,

.$j,i
$
:.
::: :.
<,. .:, .::+ . . .
-<'..'.:' .:... ..

pu b!lciln$;,get1d
:1
() '(
re.Ku.'&n
.
id;
.'.:
.
.

.
.

..

..,;

,.

F:

..
......::.. . ....c.:'i
.
. . . .. >-:...::<-

.: ;

; i -! .
.

:I :

. .:

$. ;,
!:.:,,

. . . ..
.. ,

.
..

public void setf d(int id) (


this.id = i d ;
public String getPersonName () (
return persoflame;

public void setPersonName (String personName) {


this.personNarne = personName;
.,
Lara Technologies

i.

'

public in t getPersonAge () (
return personAge;

public void s e t ~ e r s o n (int


~ ~ epersonAge) (
this.personAge = personAge;

5. Now develop one hbm file for every Pojo class in one package.

In hibernate with out primary key we can't develop any table.


In hbm file we want to take care about ail attributes for creating table.
In persons table we want to make PERSON-ID column as
autoincrement and primarykey then use id and generator tags.

<propert.j nam e="personName " co7um="PERSON-NA4\1E11!>


<propefiy name="personAge" coiumn="PERSON -AGE"/>
</class>
</hi bernate-mapping>

6. Now develop one client progsamm'.

package com.1ara;

Lara Technologies

080-41310124

-10
r

- u r e ~ % oaq)
~ d unJ pur? ( p [ b s I C ~a*!)aseqelep aq4 JAeJsMON

.L

f() uorssa~uadoys= uorssas uorssas


'() ~ G o J ~ ~ J u o ~ s s ~ s =JS
~ I hrol3e+.po~ssag
!~~-~~uo~
a)euJaq!H uo!ssas aq* uado *z//
:,,,

Defetinp a recrd through Hibernate'program:

Developing a simple helloworlij stand alone application by using


MjrSql database.
1. Go to eclipse and create one core java related project.
2. Now update the buildpath with hfluernate3,jar (i.e core hibernate) ,
jar files from !ib(hibemate dependence:.jar files) and the Driver jar
file.

3. Now develop hibernate.cfg.xm1 file inside src folder


.. . .

<?xml version='l.O1 encpding='utf-8'?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernat.e.mhematr Configuration DTD 3.Gi1Z'pj"
. ..
"http:/hibernate:~~brceforge.net/hibemate-configuration-3
.O.dtdll>
I

..:;

. .

<session-factoiy>
.'..
.

... . . ..
.

<!-- Dztabase connection settings -->

<property name="corinecti on.di-iver.-classw>


-- . com.mysql .jdbc.Drive;</property
<property name="co~e.ction.url">
.
jdbc:m ysql :/!l o c a l h o s ~ ~ ~ & a ~ / ~ r': o ~ e f i ~ ~
<property name=llconnection.usemame">root~/pro.pefi~~
<prc)pe~~y
name="cormection.pas~word">~/prop~>
.
; .

..

. ,. . :

<!-- JDBC comection pool (use the built-in) -->


<property name="connection.pool-size"> 1</property>

<!-- SQL dialect -->

<property name="dialect">
org.hibemate.dia1ect.M ySQLDialect</property>
<I-- Enable Hibernate's automatic session context management -->
<property name="cun-ent-session-context-class">thread</property>

<!-- Disable the second-level cache -->

<property n'ame="cache.provider
..... : class1'>
org.hibema~k~.~ach6.~o~ache~rovider~/property~
. ...
.

..

. .

<!-- Echo all executedSQL tojstdout


...
--> <property name="show-iql">tiue</property>
. .

<!-- Drop and re-create the database schema on startup -->

<property name="hbm2ddl.auto">create~~property>

. -:,. . .....
. .. .. . :

..:I<

. . . . .

....

:,4. Now create ' ~ i ~. ..~.....i l i a ~ e ,. .s. . t. r u cand


t u rdevelop
e
a Pojo object.
.....
.. . . .. . . . . . , . ..:,
.
.
'
:
.
'
.
,
..
.
....
......
...
::
... >.<$G!. g ;?.:>.: ,:i : .:>.:
.
.

.,:

...

....

>. .>

,...

... . .: .

"'

*+.

.+...>.:

+,

;Ti, ,.-,.a

-l

.:.

. . . . . . . . ,... ,: ;
4...

7..

.Y

'

'

:-

-::

>.>..:.

:: .,.

...

..-. ' .

.
.

.
...

package c6m;lara;
..,.
pu$lie
..,.
-.
( !;:!,r i:::; class@e~son

. . .

,:

4 ...? ..
...........
>i !:.
....
,:-:.' .....
...;;.

i ;,.:,

'

." .;

..<:-. , >: .; ...v

. ;?

...>...*.".a

d..:5'

..

.g<!,:,f5

'

.. .~.
... ..
.. ..

.. ...
.- _
-,, ,
.'L

'. >">.

-,.,.....
.siphlv,ife:,,nty
..-.. ::!.-..:.'

. .....
.~.<:
.r,$
.?.:

.,

..: 4.:; : )t. zi:5:.


*%:'. ......

.:'.. ..

:. .. . . . i. . .

<.. ,

:. ,::!:

i.

i.

We4y.qtto crate table:fd:i+JPetsori


:with~.&l.ixnn
names as
. . . . - :..<
... . . . . . . . . . . .
(Person-~ D.;. &
R S-NAME, P I Z ~ O~....
N~ ~f $.:;; ~ b.. . i develop
$ i ~ ~ tone Poj
;;,,.: ~
. EON
..,,..
..Lr.'..-.
. . ! +:.i.
....
.,.
. . .
class with all'~thesi:,
.....,..
attributes
.:
.

'...I.

A.

.........
*. .. .
.. .:..-.
. , '.:
r. .! ...

...
.

:?.;<;

. .>.
. . . . .

p m ~:, a!:' t eString:per'soiame;


...
. . . . ...
private:
i.nt
pers&Age;
j;;
I
. . . . . . .....
..
..,,;

..

<

hi-

.........

G&:,.

.,
... !

:.;:

>
i

_I

..

....I..

public void setId (iii id) (


thisid = id; : i . .:.. .;..
"

public String getPersonName () f


return persodame;

1
Lam Technologies

.. :... '..- :

. . . . .
:. ,i,?
, .:
. ;

.5

. .

< ,

' \ .

public in t@ffd () (
retum:id; . . .
..::

. ...:. .
. ,<.'
> i ..:
: . ,..
..:: . . .,: .. p:?.,..; ,.:

_ I

i:.;

.< ' ,.,

.
..

..

public void setPersonName (String personblame) {


this.pe~-sonName
= personName;

public in t getPersonAge (
return personAge;

public void setPersonAge (in t person Age) {


this .person4ge = personAge;

5. NOW develop one hbm file for every Pojo class in one package.

In hibernate.with out primary key w e can't develop any:table.


In hbm file we want to take care about all attributes for creating table.
In persons tablewe want t ~ - m a k e - ~ E R S-ID
o Ncolumn as
autoincrement and primarykek2jihen:useid
...
.
. . ...
and generator tags..
,..:.:
.

!i' . . ' ,

..
. ..

>,

! .>

.'

:,.

.
.

.?;
"

. .. 4;..._ ...
., ..
: .i

.
.

..

. . :..
<?xm] version="l:.o"?>
.
<!DOCTYPE hibeinate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3 .O//ENV
"h~:/hibernate.sourcefoge.netkibemate-mapping-3.~.dtd11~
<hibernate-mapping>
..

. ..:i .
..

<class name=~~6m.lara.Person"
table="PERSONS">
<id name="i& co]umn="PERSGN-ID">
<generator class="native"/:
</id>

6. Now develop one client programm

Lara Technologies

080-41310124

package corn-Iara;
import org.hi bernate.Ssssion;
import org.hibernate.Szssi~nFactory;
import 0rg.hibernate.c fg.Configuration;
public class Manager (
public static void main (String [I( args)
Person pl = new Person 0;.
p l .setPersonName ("RAMESH");
pl .setPersonAge (29);

11 1. Configuration
Configuration config = new Configuration 0;
config.configure 0;
.

.... .. . . .
, .

<

...

...

..

. ....
.

'Person pl = (Person)session.ioad(Person.class, new


:hteger(id));

*.~
>

113. Start the Transaction

I:.

.. :...
.
.

';112..ii)'fien the session Hibernate


~ e s s % n F a c i o ~f=~config.buildSessionFactory
r~
0;
Session session = sfopensession 0;

.: .... .. . .
y,< .;
... ... ..
. . ...

- . ..

..: . . .,

.. .

., .

. .
.. ,. .. i
, .. . .
.

.:

..
~

.;.:
...

...,
.. . .

//.1.;~;&the Transaction

.:..

ses$i&.de~ete(~l);

. .

..

115.:Commit
...- .
the trinsaction
sess~pn.getTransaction~().co~mm~t
0;
;.,c,.:

//6. Close the session


session-flush ();
session.close ();
System.out.println(" Deleted a record from table.");

Lara Technologies

7. Now start the database (i.e MySql4) and run the pro,oram.

How to develop in web-app:

..

..

.. . .,. .
,t,

and we want to create table


In this application we are using
.
for PRODUCTS with columns
.
PRODUCT NAME,PRODUCT-PRICE,PRODUCT
QUANTITY and
;...
* , , .

., .

PRODUCTID.

<

.,-

??

...
. .. .....

,t

i.

.
.
I

and we wanTio insert,delete and edit the already stofedfecord.


.........
. .

. .

'

1. Copy all relavent jar files(i.e corehibernate-jar,


hibernatedependence-jar files, driver.jar file) in to-the "lib" folder
of our web:application,
2- Now develop hibernat6.?fg.pfilhb
. . . "src"
. . .
folder
. . ..
!
..,.

::

......
I.- . .,
..............:...
'2..
. . . . . . . . . . . . .. ' - -. .. ..

2. .'

'

'

.. . .. .. .

. . . .

....

... -

'.

> .. . ...

..

. . . ..,..
*; !.

.:; ;,:;;:! ,>.:, ,

.?:

<?xml version=~~1.O1
encoding='utf-8'?>
:i........
...: . : .
, . . ... .
. . .. .
<!DOCTYPE fiibete-configuration PUBLIC
"-//Hibemote.Mibemate Configuration DTD ~.o/EN"
"h~p:/hibemate.sourceforge.net/hibe~on-3-O.dtdt1>
'I

-:.

,.

.
,

<session-factory>

,..
~.

...>

<hi bemate-.configui&ion>
.

:. +:. . .,
.
.
. .. .
:....... -:
. .

<!-- Database co.mection settings .--hi:


. . .
:. .
.<;'
. :.
- .>-:., :. .
<property name=ttconnection.driver~
-i ~ l a. ,:tsl?.
.,,:
s .;,::,,:.:.
..
. '...
com.mysq1.jdbc.Driver</piopei-ty>
. .,
....
.,
<property name="connection.url">
" :

.?!.

sb:

:I

>.

dbc:mysql://localhost~lara~/property>
<property name="connection.username">root</property>
<property narne="connection.passwo~></property>
<!-- JDBC connectioi~pool (use the built-in) -->
<property narne="conneciion.pool -size"> 1</property>

<!-- SQL dialect ->


<property name="dialectn>
org.hibernate.dialec~~~~ialect~/property~
<!-- Enable Hibernate's automatic
.
session context management -->
<property name="cu~ent
-siiii&L:
.-. context-class">thread</propeky>
,

. . . .

.......
.r

-*,.

,::;

'. . ., . . . .
<<,.

.:

<!-- Disable .the seCdnd-Jevelcac&$ ......


,..
<property . narne="cache.provider-class#3;
:
.; .,.; ..
..:.: ; -- ..
. :org.hibernate.cache.NoCacheProvider</property~
. . .

. . .*

.-.

. . ....
.
.....

. . . .

% .

..
<!-- ~ C. h. all
b execut~d~SQL
to stdout -->
~property~name='show
-sqln>true</property>
:. . :
. .

. ....

<!-- ~ r o ~. . .;. &re-create


d
the database schema on startup --.>.,i..
<property n i ~ ~. . =. . .:. .h. b ~ 2 d d l . ~ ~ t 0 " > ~ ~ d a t e < / ~ r 0 ~ e ~ >

-.

4.:::
.....

.....

3. N.ow:create
on$,package
.....
structure in "src" folder and deveiop
one
:., .........
. . . .
.-..
....
Pojo .c!aGsL;
. ..
....
..:".
:. .
. . . ..>......
.
.?.g;:::p,a
.:;
c b ':@
com,!ara;
.
:.
.
--..........
:.
::
. .I?:,. . .

, .
.. .
.
. :.,

.r

,;:

?..

,.

At?.

y<.:.

.?..,

....
....-... ...

: :

..:.....
,-, . .. . . .
A:..

::.

..

.
. .

. . C...2..
...

.<l
.:

.. .. .;,..

...

pijljJib..:class'Pi.odu&:~.:;
,..
- . : ..,. .....::
( -,?.: < :.:;!
;

:
..,,,> ;...

,:.

v-

,:.

'

,,,
;, ir; * , A

::
.

private int id;

j.:,..

' I

. 5 . . . ..:. . ..

. .: .
. . .

.< :.:.
. . .i.
"\.
I

'

.:,..
:I.:

.
,>

priva*g~tringproductN&e;
':

. .
,'

priva&:double product~~ic6i
private int pro,ductQuantity;
,.

.
.
%
:

-.

;',. .'< . , .

.::2: . .
,.....
..
: ...

....

'

int get~a(l'(.:- 5
. . . . ..' ;'
return id;' ' .;.: .$

. . . ..

':

,.

public void set~d(intid) (


this.id = id;

'

,. .
....

."!

. . .

..
.....
....

public String getProductName() {


return pi-oducWame;

public void setProduct~ame(StringproductName) (


this.productName = productldarne;
public double getProductPrice() {
return productprice;

public void setProductPrice(dou ble productPrice) {


this-productprice = productprice;

public in t getProductQuantity() (
retu rn productQuantity ;
. .... ..:. ...;,.... ...
.

...'.;
i:.

..,, > 3 .

: ,<>

'~

;.

public void setProductQuantity(int producfQuantity)


(
$, Y:'!
this.productQu2ntity = produ~tQuantity~.,~
;';
,

.,

4. Now develop hbrn(Product.hbrn.xrn1) file for every Pojo class.


".

..
',.

.. ..

.
.

<?xrnl version=" 1.On encoding="UTF- 8"?>


. . ..
.. . ::.
.
<!DOCTYPE hi bemat e-mapping PUBLIC
..
:.,.,.
"-/Mbernate/Hibernate Mapping DTD 3.O//ENW
"http:i/hibemate.sourceforge.net/hibemate-rnapping-3.~.dtd":'
....

:.,..G

::,.
. ,

. .?.
.>.:
.,

.?i,

2t.,t!>

Lara Technologies

5. Now develop one Jsp file and use it

add.jsp page is-forinserting the values into the table.

....

.,. . .;
. . .,.,.
:,..

;:ce

- / "

updating the already existing record.

kdit.jsp
.<.., page ..;. ,?:
.
:.

.<

. .
.

c, i?!.:;::.:. .
:..
. ",$, ,>...::... ... <,:....
,
l.

:.:

''

ed it.i$+;,
.

.ii

&:: .......

.*.f?i
*:., ?
-. ';. ..:&p[:$:
.;.<:;;;:
.:
.:
.::;x;

..:

. . . 2. .?'.
.<:<,;

,,

;i.

. . . . . .

,:,>..

.>,;;c:t,,+,

*.A, i.:

<..,>>

<\

'

delete.jsp is for deleting the record from table.


Lara Technologies

080-41310121

delete. i s p

3. Develop servlets for every jsp pages.


Insertsewlet. java

... .

2. : .

.. .=..
...

.. . .

p c k a g e com.lara;
. .

.
import j ava.io.IOException; ..
importjava.io.~rint~rit&..
. . . .. ..... .. . .. .. . . . . .
import javax.servlet.~~rv~~t~~~e'~ti6n;
. . ..<
,. .......
. . . ..:. ..:
im poi~j;avax.servlet.httPP~tt~~~,irt-let~e~~est;
.
..
import jz~ax.sen~let.htt~.~ttp~ervlet~es~onse;
.. . .: .
. . .. ... .. .. . . .
.
import org.hibernate.Session;
. . ...
. .. ..
..
. . . .
import orghibemate.SessionFactory;
import org.hibemate.cfg.Configuration;
. . ... ..:
.. .
<..,.

;,

.....
. .
.: . . :

. .

. .

.,...>*.

'

; .

..

>..

.
~ .
.
. . i.
. .
. ,

.I

'.:I

..

public. c l a s s ~ , ~ n ~ e r t ~ eextends
r v l e t javax.servlet.http.~ttp~:e&let
....
implements javax.servlet.Servlet (
.
static final ,long serialVersionUID = 1L;
public ~nsert~ervlet()
( -1,
. . . .
super();
. .. . . .
i
protected void d o ~ o s t ( ~ t t ~ ~ e r v l e t ~ erequest,
c@est
HttpServ1e.tResponse response)throws
..
ServletException, IOException
.

String pName = request.getParameter("productNamelI);


String pPrice = request.getParameter("productPrice");
String pQty= request.getParameter("productQuantity");
Product pdr = new Product();
pdr.setProductName(pName);

Configuration config =,new Configuration();


config.configure0;
SessionFactory sf =~config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();

-',isession. close();

. .

package
com.l$.a;,~:::
..........
.+>. ;,,:,
>;.!
-.
:

. . . .. . . . . .

..:. .$..:<;..:
.

'

,:;.

. - . : .:
im p o r t ~.........
5;~~~~o~IOExce~~on;
r

..;..::.....
............

<..?*.

..;C.; .;
.#

..,::
. .
,.

. .
.':.'

. .

...
. .......
.

.....:.,.. .I...

. .

import j a + & i o . ~ : ~ i n t ~ r i i kzy.i .;: ,..,


....
import javax.~~$$51et.~ervlet~x~~,<tion;
import javax.s~&lkt.http.~ttP~enil~t~equest;
.....
.:
import jstvax.servlet.http.HttpServIetResponse;
import org.l?i
- bernate.Session;
import org.hibemate.SessionFaciory;
import org.hibemate.cfg.~onfiguration;
......

;.

public class UpdateServlet extends javax.servlet.http.HttpServ1et


implements javax.servlet.Servlet
{
Lars Technologies

static final long serialT7ersionUlD = 1L;


public UpdateServlet() {
super();

protected void d o ~ o s t ( ~ t t ~ ~ e r v 1 e t ~request,


e~uest
HttpSepletResponse response) throws ServletException,
IOException

C
String id = request.getParameter("idn);
String pName = request.getParameter("productName");
String pPrice = req~est.get~ararneter("~roductPrice");
String pQty = request.getPararneter("productQuantity1');
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory0;
Session session = sf.openSession();

session.beginTransaciion();
Product p 1 = (Prociuct)session.load(Product.class,
Integer.parselnf(id));

Printwriter out = response.getWriter();


out.println("PR0DUCT UPDATED");
out.println("<br><a lirePindex.jsp>HOME</a>");
out.close();

Lara Technologies

080-41310124

PrintUTriterout = response.getWriter();
out.println("PRODUCT DELETED");
out.println("<br><a hreeindex.jsp>HOME</a>");

-.

4. Now 'start the data base(i.etMySq14)andllrun the "index.jspn.

..

.. ..

. .?. . . .

. .

'.

One mo&:~a;am~le
..
for how to devlop hibernate $$$in web-app
..
by
doinp all the o ~ e ~ ~iSetizsert
i ~ ~ s ~Fdatz,!is$,s~~~~&~
,...

. - ...
. , '; ..

In. this application we are using Oracle10g database and we want to


create table for ADDRESSES with column names as ADDRESS-ID,
ADDRE~~S
HOUSENO; A D D ~ S S;STREETNO,
.
ADDRESS-CITY,
ADD$&~sT~~E, ADDRESS
-CO-WRY,'.. . and.,
,..
ADDRESS,-PINCODENO.
.

..

. ..

. ,.

hiberna te.cfg.xm1
!
...

... .

..
<?xml:~y~~sion='
1.0!&icoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-/Hi bernateMib e r n a t e ~ o n f i ~ u r ~ tDTD
i o n 3 .O//EN "
" h t t p : / / h i b e r n a t e . s o u r c e f o r g e . n e t / h i b e ~ a t i o n - 3.O.dtdn>
.

<I--Database connection settings -->

<property name="connection.driver~class">
oracle.jdbc.drive~OracleDriver~/propert~>
<property name="connection.url">
jdbc:oracle:thin:@Iocalhost: 1521 :XE</propedy>
<property narne="connection.usernarne">system<iproperty>
Lara Technologies

080-31310124

-.

<!-- JDBC connection pooi (use the buiit-inj -->


<property name="connection.pool-size">]-4property>
<!-- SQL dialect -->
<property narne="dialectn>

org.hibernate.didect.OracleDialect</property>

<!-- Enable Hibernate's automatic session context management -->


<property name="current-session-context-class">thread</property>

<!-- Disable the second-level cache -->


<property name="cache.provider-classH>

org.hibernate.cache.NoCacheProvider~/property>
<!-- Echo all executed SQL to stdout -->
<property name="show-~ ~ l ' ' > t r u e 4 ~ r o ~ e r t y >
..

....

.. , ..

<!--

.,

.. .

...

.
..o,n!startup-->
and re-create the ditab&e schema
.

..

...

...

~prope~y?:~n~e="hbm2ddl.auto1~>upda~e</'p~op~rty>

package com.lara;

.
. .

public class Address


{
..
private Integer Id;
private String houseNo;
private String streetNo;
private String city;,
Lara Technologies

080-41310124

private String state;


private String country;
PI-ivate long pinCodeNo;

public Integer getId() {


return Id;

.
. .

public void setId(lnteger id) (


Id = id;

..

.: .

1
pu b lic String getHouseNo() ( ..
return houseNo;

public void setHouseNo(String houseNo) {


this.houseNo = houseNo;

>

. :.
.

public String getStreetNo0 (

>

,.

'

public String getstate() {


retu rn siate;
.;
public void seiSizte(String state) {
this-stzte = state;

i
public String get~ountry()'{
return country;

>

..

.. ..

public String getcity() (


return city
.public void s&tsC:ity(String city) {
this.city city;

.... %... .

public void setCountry(String country) {


this.country = country;
j

public long getPinCodeNo0 (


return pinCodeNo;

public void setPinCodeNo(1ong pinCodeNo) (


this-pinCodeNo = pinCodeNo;
1

<?xml version=" 1.Onencoding="TTTF-8"?>


<!DOCTYPE hibemate-mapping PUBLIC
"-//Hibematemi bemate Mapping DTD 3 .OiIIEN1'
"http:/hibemate.sourceforge.net~hibernate-mapping-3.O.dtd">

- .

In hbm file we are not giving any column names for property tag then it
take defaut name as property name.

add-jsp is for inserting the values into the ADDRESSES table.


add.isp

<body>
<form action="lnsertServlet" method="post">
HouseNo:<input type="text" name="houseNo"><br>
StreetNo:<input type="textWname="streetNo"><br>
City:<input type="textUname="cityM><br>
State:<ir,put type="textWname="statenxbr>
Country:<input type="textUname="countryl'><br>
PinCodeNo:<input type="textn
name="pinCodeNol'><br>
<input type="submitUvalue="ADD ADDRESSv>
</form>
</body>
search.jsp is for serrrching the particular record in the table
. , , by
selsecting the coIumn names and giving the text to search.
search.isp

<body>
<folm action="ListSei-vlet"/>
SearchCriteria:
<select name="searchCriteria">
<option value="id">AdressId<loption>
.
coption value="houseNo">HouseNo</option>
<option value="streetNo">StreetNo</option>
<option value="city">City</option>
'
<option value="state">State</option>
<option value="country">Country</option>
<option value="pinCodeNo">
PinCodeNo</option>
Lara Technoiogies

</select><br>
SearchText:
<input type="textl' name="searchText">
<input type="submit" value="Search">
</form>
</body>
InsertSew1et.java is for inserting the values into the table. If we want to
insert the servlet then
. . ..
we to :call save0 by passing the object.

...

~.

. .

..
. .,r

:..,.

~:

.'

.::.

&

.<
,:. .
.. ,::
..

, ,
. .

.<'

...

package cok.lara;
import j a v a ~ ~ . ~ ~ ~ x c e ~ t i o n ;
import java.i&P*int~rite~
ja~ax.senile~~~ervlet~xce~tion;
.
. import
.>
,;. . .,,.;.....J ...
...
.< :
. . ~import~,.javax.servle~littp;NttpS.ervletRequest;
.
..
. ,. .
~mpor~~~~y.gx.servlet-.http.~ttP~ewlet~esponse;
. . .
.
'
;.:z!:..*
.. . . .
im
p
o
k
t
~
~
'
~
g
~
~
i
b
e
m
a
t
e
.
~
e s s i o + ,:~ C ~ ~ r y ;
...;.
.-....;i~.;:t-..:,:.
. .~.
import org;hlp.emate.cfg.~onfig&ition;.
.!. 6
. . .
.,-.,
: .:>;
. . . . . . ..,.import
.
org.hikieqate.classic.Session;
.>
.. . . ..
class
InseASewlet
:
,
...:.
extends javax.serv1et.http.HttpServlet
.,:.
.r. public
_.
'implements javaxi$ervlet.Servlet {
.
&
.:: i a l ~ e r s i o n
=~1L;
~~
stati&$inal
". long ,&
<p"biic~,nsert&ervlet()
(
$$~z$*
B 7 :
.. .qg
.*gj.y..t3.%&,, pe+l@;$$
:.t<.3.a;T<$rV
3.. ... .*.2:
. . ..I... :ry
. . .:..:.
....
. .... : ...
.**
<>;.;. z . :.:. *<..?
..
"6'.,?'..
>??, ., *:;$
)
..< :. . . .
. I-".
protect6djvoid doPost(H~p.Se~IetRequest
request,
HttpSer:!etRespoii$ci1. ,. response)'th
....
rows ServletException, IOException
.
.

. . . : .
. .

..

.
.

.-::

.. . .
. . .

<

..

:..

'

.. . . .
.;
!
. . .. . . .
..

. .
::.

'

.-.I

...

..

..

* >

3.

>.

'

,:

;.

--

.I''

,:.

i,:t.;.

a.>:.

rx

,..,..-I

:. .;.

!.%-

,:.

-i,.

,:;

.A,

.I

. c .?

String houSe~o-7e~uest.get~irarneter("house~o");
String ~treetN~equest.getParameter("streetNo");
String city=request.getPararneter("city");
String state=request.getParameter("state");
String country=request.getPara,aeter("country ");
string pinCodeNo=request.getPararneter("pinCodeNo");
Address adr=new Address();
adr.setCity(city);
Lara Technologies

080-41310124

Configuration config = new Configuration();


config.configure();
Session session = sf.openSession();

session.getTransaction().commit();
session.flush();
session.close~;
Printwriter out = response.getWriter();
OU~.~~~~~~~("A
SAVED");
DDRESS
.

. .!.. :
. :...'.. ..;.. !.. .

..: .,.,<
::, ::; .:>r

;.
'

. . ...t i .
. .. .
.

.:

....

... ..,
:..>
., : !*
.

.. .,

. *.,
....

UpdateServlet.java is for editing the particular record in the table. If we


want to update the record then we want to call saveOrupdate()
,
by
passing the object.
.

UpdateServIet-iava
package corn-lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax-sei-vlet.ServletException;
import javax.servlet.http.HttpServ1etRequest;
import javax.~ervlet.http.~tt~ServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class UpdateServlet extends javax.servlet.http.HttpScm1et
implements javax.servlet.Serv1et

Lara Technologies

OSG-41310124

static final long seriali/ersionUlD = 1L;


public UpdateSer\.iei() {
supero;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
String id = request.get~ararneter("recordld");
String houseNo=request.getParameter("houseNo");
String streetNo=request.getParameter("streetNo");
String city=request.getParameter("city");
String state=request.getParameter("state");
String country=request.getParameter("country");
String pinCodeNo=request.getPararneter("pinCodeNo");
Address adr=new Address();
.

i
.

Configuration config = new Configuration();


config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

Lara Technologies

080-4131.0124

Printwriter out = response.getWriter();


out.println(llADDRESS SAVED<br>");
'out.println("<a hrePindex.jsp1>Home4a>");
out.println("<a href='ListServletl>ListRecordHome</a>");
out-close();

ListServlet.java is for listing all the records from table. If we want to list
all the records then rve want to use criteria interface or Query
interface. In this application we a r e using Criteria.If we want to create
object for Criteria interface then there is a method createcriteria ()
which there inside the session class.

Eg: session.createCriteria(Address.class);

import java.io.IOException;
i m p ~ rjava.io.Print'Clrriter;
t
import java.util.list;
import javax.servIet.ServletException;
import javax.servlet.http.HttpServletRequest;
irnpo~j~vax.servl~t.http.~ttP~ervletResponse;
import drg.hibernate.criteria;
import org.hibernate.~ession~actory; !.
import 0rg.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
"

p ~ b I i cclass L.istServlet e x t e ~ djavax.serv1et.http.HttpServlet


s
implements
j avax.servlet.Servlet

static final long serialVersionUlD = 1L;


public ListServlet() {

i s r z Technologies

protected void doGet(HttpServ1etRequest request, HttpServletResponse


response) throws ServletException, IOException

Address add= new Address();


Printwriter out = r e ~ ~ o n s e . ~ e t ~ r i t e r ( ) ;
String sc = request.getParameter("searchCriteria");
String s t = request.getParameter("searchText");
out.println(''<table bord'er='.ll>");
. . .
out.println(";=tr>.");
.
o~t.~&tln("<td>");
out.println("<b>ID</b>");
o~t-println(~:</td>");
out~println("<td>ll);
out.println("<b>HOUSENO</b>"); -. . . .
o,ut.println("</td>");
o~t~println(llitd>l~);
. .

o~t.~iin~ln("<b>~~RE~'l'N~</b>~~);
. . .!
out.printlnt:y</td>'.');
.
...!

o~t.~rintln~!'<idY);
.

. . .

'.

:~out.print]n("<b>CITY</b>");
:.
.

.. . . ..
.

o~~t;printlil("</id>");
&it'<:intln "<td>").
. . ..

.,

>:; *,.

p.:

..

,.
. . :,-....
r .

o~~j$&tln(l'<b>~~~~~</b>'l);
..
.:, .

out:$rini]n(tl</td>");
I ;

.. :.

~ut.~rintln("<td>");
:

~ut~.~r'intln("<b>~~~~~~~</b>'~);

:: -

out.prinilG("'</td>'');
.'.
. .

,o;t;ijriniln(!l,<td>'l);
.
.........
o~~println("<b>PINCODENO</b>'~);

,.,. .

.,

out.~iint]n("</td>;;); .'
out.print~hp'</tr>~~);
.
.

i5

Configuration config = new Configuration();


ccnfig.configure(j;
SessionFacto~ysf = config.buildSessionFactoryO;
Session session = sf.openSession();

L a r s Technologies

080-41310124

;:,

.;...
:s:. _

...

...

6.

' .?.!<<>?

...

Criteria ctr = session.createCriteria(Address.class)J


ctr.add(Expression.eq(sc, st));
List list = ctr.list();

for(int i=O;i<list.size();itt-)

add = (Address)list.get(i);
out.println("<tr>");
out.printIn(''<td>l1);
out.println("<a href-'DetailedServlet?recordId="
+add.getId()+'">");
out.println(add.getId());
out.println("</a>");
out.println("</td>");
out.println("<td>");
out.println(add.getHouseNo());
out.prin1ln(lf</td>");
out.println("<td>");
our.println(add.getStreetNo());
out.println("</td>");
, out.printIn(l'<td>");
out.println(add.getCity());
o~t.println("<ltd>~');
out.println("<td>");
out.println(add.getState());
out.println("</td>");
out.println("<td>");
out.println(add .getcountry());
out.priniln(":itd>");
out.println(lT<td>"j;
out.println(add.getPinCodeNo());
out.println("</td>");
out.println("</tr>");

out.println("<ltable>");
out.println("<a href-'index.jsp'>Home</a>");
session.getTransaction().commit();
Larn Technologies

080-41310124

DetailedSewlet.java is for if we select one record then it want to display


all the co1llmns from the table.for this we want to use load () method
which there inside the session class.

package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.se~let.ServletException;
import javax.servlet:http.HttpServletRequest;
import javax.servlet.http.HttpServ1etResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibemate.classic.Session;
public class DetailedServlet extends javax-servlet.http.HttpServ1et
implements javax.servlet.Servlet
staticdinal long serialVersionUID = 1L;
public DetailedServlet() (
super( 1;

1
protected void doGet(HttpServ1etRequest request, HttpServletResponse
response) t h rows ServletException, 1 0 ~ x c e ~ t i o n

String recordld = request.getParan~eter("recorc!Id''~;


Configuration config = new Configuration();
config.configure();

Lara Technologies

080-41310124

Session session = si'.openSession(


session.beginTransaction();
Address add = (Address)session.load(Address.class,
new Integer(record1d));
Printwriter out = response.getWriter():
out.println("HouseNo: "+add.getHouseNo()+"<br>");
out.println("StreetNo:"+add.getStreetNo()+"<br>");
out.println("City :"+add.getCity()+"<br>");
out.println("State:"+add.getState()+"");
out.println("Countiy :"+add.getCountry()+"<br>");

out.println("PWCODENO:"+add.getPinCodeNo()+"<br>");
out.println("<a href-'DispIayForEdit?recordId="
+add.getId()+"'>Edit </a>");
out.prir~t;~l<";a;~i.t.C='Se;eteServlet?recordld="
+add.getId()+"'>DeIete</a>");
out.println("<a href-'index.jsp'>Home</a>");
out.println("<a hreFListServlet'>ListRecordHome</a>");

DeleteServlet.java is for deleting the particular record.If w e want to


delete one record then w e want to call the delete0 by passing the object.

package corn-lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.hitp.ltittpServletResponse;
.
nm port org.hibernate.Session.Fac~~~~;
.

Lsm Technologies

056-3!310i24

import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class DeleteServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet
,

static final long sevinlVersionL'ID= 1L;


public DeleteSel-vletO {
seper();

1
protected void doGet(HttpServ1etRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String id = request.getPararneter("recordIdI1);
Address add = new Address();
add.setId(new Integer(id));

Configuration config = new Configuration();


.'; .-c.onfig.configure();
.
. .

..

...
..

. .:...

-..

.;

_ ,

..

~ ~ ~ i o n ~ , a c sf
t o=r c- ~
y nfi~.build~ession~act~)~~();
Session session = sf.openSession();

Printwriter out = response.get'?iriter();


out.println("ADDR.ESS DELETED");
- out.println("<a hre+'index.jsp'>Hor,e<ia>");
out.println("<a href='ListServlet'>ListRecordHome<i'a>");
out.close();

Lara Technologies

DisplayForEdit.java is for modifying the particular record in the table.

package corn-lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servl.et.ServletException;
import javax.servlet.http.HttpServ1etRequest;
import javax-sesvlet.http.HttpSefvletResponse;
import org.hibemate.SessionFactory;
import org.hibemate.cfg.Configuration;
impsrt org.hi5e~s~e~clsssic.Session;
.

*%

. . . . .,:
. .....
: ..

. ,. ... ..'.:..
. .

... .

public class DisplayForEdit extends javax.servlet.http.HttpServ1et


implements javax.servlet.Servlet
..
{
static final long serialVersionUID = 1L;
public DisplayForEdiii) {
super();

1
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String recordId = request.getPararneter("record1d");
Configuration config = new Configuration();
config.configure(.);

SessionFactory sf = config.buildsessio&ctory();
Session session = sf.openSession();
session.beginTransaction();
Print\Vriter out = response.getWriter();

Address add = (Address)session-load(Address.class,


new Integer(record1d));
out.printin("<form action='UpdateSenlet' method='post'>" j;
out.println("<input type='hiddenl name='recordTd' vzlue-"'
+add.getId()+"'>< br> ");
out-printIn("HouseNo:");
out.println("<input type='textl name='houseNol value="'
+add .getHouseNo()+"'><br>");
out.println("StreetNo:");
out.println("<input type='text' name='&eet~o' value="'
+add.getStreetNo()+"'xbr>");
out.println("CityW);
out.println("<input type='textt name='cityt value="'
+add.getCity()+"'><br>");
out.println("StateW);
out.println("<input type='textt name='statet value="'
+add.getState()+"'><br>");
out .println('lCountry");
out.println("<input type='textl name='countryl val?le="'
+ad8get~ounhy(+"'><br>'');
out.println("PinCodeNo:");
out.println("<input type='textl n a m & ' p i n ~ o d e ~ ovalue="'
'
+add.getPinCodeNo()+"'><br>");
out.println("<input type='submitt value='UPDATJV";
~ut.~rintln("</form>");

. . . .

...

....
....
.

What are all the algorithmsforattribute "class" of "generator "tag of "ici"


tag ?
9 The types of algorithms are:
1. hilo
2. seqhilo
3. uuid
Lara Technologies

4.
5.
6.
7.

guid
sequence
identity
select

Eg: For testing the algorithms; using OraclelOg database

<?xml version='l.O1 encoding='utf-8'?>


<!DOCTYPE hibemate-configuration PUBLIC
"-//Hibernate1Hibemate Configuration DTD 3 .O//EN"
"http:/lhibemate.sourceforge.netlhibemate-congration-3 .O.dtdn>

<!-- Database connection settings -->.


<property name="connecti on.driver-classu>

oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost: 1 52 1 :XE</property>
<property name="connection.usemame">system</property>
.
<property name="cormection.password">great 123</property>
.

<!-- JDBC connection pool (use the built-in) -->


<property .name="connection.pool-size"> I </property>
.,

..:

..

.. .

<!-- SQL dialect -->


<property name="dialectn>

. ..

>
..

..

. ::i... :

_ ....:. ... _.,...


org.hibernate.diafect.~raclb~i&ct</property~
,. ..

.. , .:?
? .

<!-- Enable Hibernate's automatic session context management -->

<property name="current-session -context-class">thread</property>


<!-- Disable the second-level cache -->
<property name="cache.provider-cl ass">

org.hibemate.cache.NoCacheProvider </property>
Lara Technologies

080-41310124

46

<!--Echo a11 executed SQL to stdout -->


<property name="show-sqlN>@e4~roperty>

<!-- Drop and re-create the database schema on startup -->

<property name="hbm2ddl.autot1>create</property>
<mapping resource=l~co~larg/Book.hbm.xml"/>

.
.

.. .. .-... ..,a. .

. .

priva$<:bteger
id;
: ....
.............
pri~ate,;Sp-i~ng
, ...
.......
boomame;
........
private Stibg.
.,,... .,:
.. , bookAuther;
private D&@@.
bookprice;
I."

. ,

>-;-.r .<

. . .. .. .

.. ? - :

L.

. . ,

thii:idi=:id;
......

.; . !1
.-'.,:.
. . . . ..
...,
.b :. ..
. '.' Li.y

>%

.:+

'

.~. 3

. . . .:. ..
.

.,.

::.:
. !

public String get~.ookName(){


return bookName;

>

public void setBo.okName(String bookNarne) (


this-boomame = bookName;
......
...
%
,

.>

.,

.
.

public String getBookA~ther()~.(i!.


.. .
return bookAuther;
> .

.,-

public void setBookAuther(String bookAuther) {


this.bookAuther = bookAuther;

1
public Double getBookPrice() {
return bookprice;

yu blic void setBoukPrice(Doub1e bookprice) {


this.bookPri ce = boolcPrice;

<?xml version=" 1.Oll?>


<!DOCTYPE hibemate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3 .O//ENV
"http://hibernate.sourceforge.net/hibernate-mapping-3 .O.dtdW>
<hibernate-mapping>

Liwa Technologies

080-41310124

Boomame :<input type="texiXname="nmenb<br>


BookAuther :<input type="test" name="authern/><br>
BookPrice :<input type="texi'I name="price"i><br>
<input type=''su bmit" value="su bmi t"/>
</form>

package com.lara;
. ..
,

import java.io.lOException;
import java.io.PrintWriter;
import javaxkerv1et.ServletException;
import javax.servlet.http.HttpServletRequest;
.. .
. . :.
:fmport javax.servlefrhttp.HttpServ1etResponse;
>..
..:
iim port.org.hibernate;SessionFactory;
im'port org.hibernate.cfg.~onfi8uration;
import~~o~g.hibernate.classi~ession;
. ,....:
:_...

.::,

';?

. .,.
.,. ...

.
. ...> .. .

public clas~hJ@,ook~ervlet
.....:.
.

'I:

1'

..

..

..

.
..

public v o i d ; ~ d d ~ o o k ~ e r v l e t ( )

i
.super();

,;;:

:
i
,

\ .!: ..'
I.',

..

..:,,:.,:

.;'.

!;.:

protectedjvoid
.,:
doPost'(HttpServ1etRequestrequest,.
HttpServletR&sponseresponse) throws Ser~letException~
IOException
.

...

String id=reqvest.getParameter(i'id");
String name=request.getParameter("name");
String authe~request.getParameter(c'auther");
String price-request.getPara~neter("price");
Book book = new Book();
bbok.set~d(lOO);
book.setBookName("JAVA");
Lara Technologies

080-41310124

Configuration config = new Configuration();


config.configure("c~nfig/hibernate.cfg.xml'~);

Session session = sf.openSession();

session.ciose();
Printwriter o ~ t = r e s ~ o n s e . ~ e t ~ r i t e r ( ) ;
Outtprintln("check in the database.");

All algorithms will *notsupport all the databases only few algorithms
only support particular databases.

Among these some more algorithms is there they are


native,assigned,increment these algorithms will support all the
databases.

i a r a Technologies

How to separate cfg-xml from src folder to separate folder.

Create one folder where ever and copy that cfg file into that folder then
come to the program and at the time of configuration give the path of the
folder.
EG:
Srcl
1----cfg[
1--hibernate.cfg.xml
Now come to the program
Configuration config = new Configuration();
config.configure("config/hibernate.cfg.ml");
..,

Cascade types:
. .
. .. .
7
.
:....:
.. .. '
:.
.. .:,.. . . . .... . , . . .
,

.r

. ,

... . ...

.
.>. :
. ... . . .%?-*.
.. ..:.
.. . ..

..

. .
.

: :.

.. .

'.':.:;.:

~all,~~~a$e,merge,save:update,delete,lock7refresh,eviet7replicate.
.
,
? . /

.,

..!.

. . . , 9

.. .
. .
. 6 ',<, .

..

'

.:.< ..:>.':
,

.
.

. . .:
~onstra~~,ed;:(optional)
specifies that a:foreign key constraint on the primary
.

.:

.:.

key of the mapped table references thetable of the associated class. This
affectsthei.order
.:-:
in which save() and delete() are cascaded, and
.:option
.
: determines whether.the association may be proxied (it is also used by the
schema export toblf, . ..
.

. ...
.

.>

.. . ...

....

If we
constrain~d+'false" then in USER DETAILS table we will not
get refren&key .i .e
. :foreignkey
i
but we will getdata
The generatgd:qjiery is ; ;'.:,.
create t a ble USER-DETAILS
,. .

..

...

I'

"USER-ID" VARCHAR2(255),
"USER~EDUCATION" VARCAAR2(255),
"USER-DESIGNATION" VARCHAR2(255),
b'USER-ADDR_'ESS" VARCHAR2(255),

PRIMARYKEY(''USER_ID7')ENABLE
)*
If we give constrained="true" then we will get refiencekey i.e foreignkey
and data
create table USER-DETAILS

Lara Technologies

080-41310124

:.

"USER-ID" VARCHAR2(255)NOT NULL ENABLE,


"USER EDUCATION" VARCMAR2(255),
"USE~DESIGNATION"
VARCHARZ(255),
"USER-A4DDRESS"VARCHAR2(255),
PRIMARYKEY ("USER-ID")ENABLE
CONSTRAINT "FK24CC75E74607B17"
FOREIGNKEY ("USER_ID")
REFERENCES "USERS"("USER -ID") ENABLE

s are mainly threee types they are:

1. Relational Mapping
(a) One-to-one ~ a ~ p i n g
(b) One-to-Many and Many-to-one Mapping
(c) Many-to-many Mapping
2. Polymorphic Mapping.
(a) One table per Class hierarchy
(b) One table per Sub-class
(c) One table per Concreate-Class
3. Component Mapping.

I.(a) One-to-one map pin^:

hi bernate.cf~.xmi
<?x;il version=: 1 .Of encoding='utf-8'?>
<!DOCTYPE hibemate-configuration PUBLIC
"-//Hibematemi bernate Configuration DTD 3.O//ENH
" h t t p : / / h i b e m a t e . s o u r c e f o r g e . n e t / h i b e ~ i o n - 3.O.dtdW>

Lara Technologies

- -_ l - I I

080-41310124

. .-

.,

--

52

;TT

'

<!-- Database connection settings -->.


<property name="connection.driver-class">

oracle.jdbc.driver.OracleDriver</propeny~
<property name="connection.urlrr>
jdbc:oracle:thin:@localhost: I 52 1:XE</propem>
<property name="comect ion .username">system</prope~~
<property narne="comection.password">great123</property>
<!-- JDBC corm'ection pool (use the built-in) -->
<property name="connection.pool~size">l</property>
<!-- SQL dialect -->
<property name="dialectH>
.
org.hibemate.dialect.~racle~ialect</~ro~ert~~
..

..

<!-- Enable Hibernate's.


automatic
session context management ->
:. .
.
<property name=ncun&*ti'
session
- c . o ~ ~ rc,ltz s s n > t ~ ~ z ~ ~ < ~ 3 i ^ - G F E ~ y > ~
.
.

.- .

..:.. .

. .

<!-- Disable the second-level cache -->


<property in~e="cache.provider-cIass">
..

.
'

,. .

.*.

.-

..,
5 .

org.hibemate.cache.NoCacheProvider</property>

:. .
.. < < ..:
'.i. .., !?
'

<!-- Echo all executed


*. .
SQL to stdout -->
<property narne=''shcw
,!
-sql">true</property>
.
..

,?

.. . .

. .

.:

..

.
.
.
._
.. ... .. . .

8 . .

...

<!-- ~ro~&nd.i&-creite::the
.. . .
database scbema on startup -->
<property na~e="hbm2ddl.auto">create</~roperty>
.
.
.

,.

Eara Technologies

package corn-iara;
public class Person
private String personld;
private String personFirstName;
private String personlastName;
private Integer personAge;
private Mail mailld;
public-String getPersonTd () (
return personid;
1

public void setPersonId(String userId) (


this.person1d = personId;

t
public String getPersonFirstName() (
return personFirstName;

public void setPersonFirstName(StringpersonFirstName) (


this.personFirstName = personFirstName;

public String getPersonLastName0 {


retu rn personLastName;

public void setPersoriastName(String personLastName) (


this.personLastName = personLastName;

public Integer getPersonAge0 {


return persod-ge;

void setPers0~,4ge(~lnteger
personAgej
this.person,.?lge = personAge;

! r ~ biic
ti

>

r.

public Mail getMailId() (


return mailId;
}
public void setMailTd(Mai1 rnailId) (
this.rnai!l'd = mailJd;
La re Technofogies

880-41310124

./

--

54

-.
,

IT-

'

package corn-Iara;
public class Mail
{
private String mailld;
private.Person person;
private String password;
priva t i Date createdTirne;
priva'te.String
.
personId;
.

public String getMailld() {


return mailId;
...

I.

.-, :.,

..

. . ..

.
.

.I

:, public void s e t ~ a i l l d ( ~ t ruserld)


in~ {
.....
. . .':.B<
.<;this.
.......
rnail1d
=
ri.ltiil1d;
...: .
) -.<.;T
.:,..:{:>>'...:..
,

,.

-.

pu blkiP~~io,n
......
., getperson() (
ret.ultn-person;
.:,.
:...I*:.'<.

<.,.

.:.
. ,
.......
. . .. . .. .
.,j-, . ':.. 7

public void:~se~~erson(Person
....
person) {
this. pefson
= person;
. . .
' ;.
)
.. I.:.i;>,p::. . .f;.?.+::::
..
..: ...- ..
pu a~c~stri~g~~~<tP~ssword~)
.

\T

,;:

>..<..

. *. .?s.

+.,.:,<.

:.

~6ku~.,password;
. .:....
... *.,....
. .;...
.........
......
.'.,.. . .. ,.! .. .,.

;.

..

public void setPassword(String pqssword) {


this.password = password; .

public Date getCreatedTime(1 (


return createdTime;
j

pu blic'void sctCreatedTime(String createdTime) i


this.createdTime = createdTime;

public String getPersonId() (


Lara Tecllnologies

080-41310124

return personId;

j
public void setPersonId(String personld) {
this.person1d = personld; . ,
'

>

.=

<?xml version=" 1.Owencoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hi bernate Mapping DTD 3 .O//EN1'
"http://hibernate.sourceforge.nethibernate-mapping-3 .O.dtdn>

<property name="personFirstiVamel' column=" PERSON


-FIRST NAMEM/>
<property name="persor&ast~ame" column=" PERSON -LAST-NAME."/>
<property name="personAgen column=" PERSON AGE"/>
<property name="mailldl' column=" PERSON -E ~ I L " I >

<?xrnl version="l .On encoding="UTF-8"?>


<!DOCTYPE hi bernate-mapping PUBLIC
"-//'Hibernatemi bernate Mapping DTD 3 .O//'ENH
"http://hibemate.sourcefbrge.net/hibernate-mapping-3
.O.dtdM>

<property name=" password " colurnn="PASSWORD "I>


<property name=" createdTirne " column="USER EDUC "I>
<property name=" personld " column="USER-D@IGNATION"&

package com.1a1-a;
., , .

import org.hibematk.~ession;
.
import o r ~ ; b ~ a t k . ~ e s s i o . n ~ ~ c t o ~ ;
import org.hiber&te.cfg.configuration;
:.:

public class Manager

public static void main(String[] args)

.Mail mail = new Mail();


mail.setMaiIId ("abc@+bc.com~);
mail.setPerson (p 1);
'
mail .setPassword("abcxyz");
mail.setCreatedTirne("22-jan-2009");
mail.setPersonId("p 101");
Lars Technologies

080-41310124

Person p 1= new l'erson();


p 1 .setPersonId("~~
101");
p 1 .setPersonFirstName("abcl');
p 1 .setPersonLastName("def ');
pl .setPersonAge (28);
p 1 .~etMailId((~~abc@abc.coin");
Configuration config = new Configuration();
config.configure();
SessionFactory sf 4 config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction0;

<?xml version='] .Of encoding='utf-8'?>


<!DOCTYPE hibernate-configuration PUBLlC
"-//Hibernate/Hibernate Configuration DTD 3 .O//ENll
"http:/hibemate.sourceforge.net/hib~guration-3.~.dtd11>

<!-- Database connection settings -->


Lara Technologies

080-41310124

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool-sizev>1</property>

-->

<!-- SQL .di!al,eci


. .. : . . ...
<property .name=''di,alect">
org:hibernate.dialect.0racleDialect4property~
.:,

"

,:

'

...

<!-- Enable~ibemate'sautomatic session context management -:>


-session-context-class">thread</property>
<pr~pert~;n~~,e="current
........ ..
.....
. ..

. . . .

. .. . .. . .. . .
' - . .:. ,.;

<!-- Disable the.s.e&?jnd-level


......
:.. ..
cache -->
.:*; !.
<property
name="~$.~~eeffi~oVid&
;;,c]assW>
.
.
.
.
..;;':C
or~:hlbernatk.cache.~o~ache~rovider</~ro~ert~>
. .

. .,<*>>,.
A

i!

'

.
.
.7..

.$- .:

<!-- ~ ~ .....L7
h.)?. & & 1 1SQL
# ~to~stdout
~ ~ -->
~ ~ ~ d
... hS;2:*.:
<property dgme="show
.........
-,sql">true4property>

:.

?,:..e!,;.: .....
,$.:.
.,<:.. .,
.
$.,:7...:,?,.:;
,,,.$,..

.... i.,.....
.

<k,Drop an&xe&reate
the database schema on startup -->
.. '
<pzoperty
.
.
.
nard~=~hbrn2ddl.auto">create</property>
....
>,! '

; . :

>

. .

,>..
...
....
<
,
. . .:i
:.-,...
: . : .. .. .. .. .. . :..

. .. . . .;.,;

,..

*'lh!..;.
. .: : . : . ' . hbm.xml"/>
<mappi,n~~~spurce~.~~ci"om/Iara/User.
..<:. k:.,. =...:>. :.,. .r".i.;.
. .......
...

.?,
.,.

<mappingi:,res~urce=''~c8mjlara/(
......
<.:. . .:=.,
.UserDetails.hbm.~l"/>
. .
.>..,.
.

-,a
;

.&]::".:, ...: .. .
.>
:&
;

. .. . . . .. .' ... . .
,

<.%?libemate-configuration> 7
Vser.fava
.-C

package corn-lara;
public class User
Lara Technologies

.,?,

private String userId;


private String userFirstName;
private String userLastName;
private Integer userAge;
private String userEmai1;
private String userMobileNo;
private UserDetails'userDetails;

..

public String getUserId() {


return userld;

>

public void setUserId(String userId) (


this.user1d = userld;

public String getUserFirstName0 {


return userFirstName;

public void setUserFirstName(Stri-nguserFirstName) (


t h is. u s e r ~ i r i t ~ a m
=euserFirstName;
return userLastName;

public void setUserLastName(String userLastName) {


this.userLastName = userLastName;

>

public Integer getUserAge() {


return userAge;

public void setUserAge(1nteger userAge) (


this.userAge = userAge;

>

public String getUserEmail0 (


return userEmai1;

public void setUserEmail(String userEmai1) (


this.userEmai1 = userEmai1;

pu hlic String getUserMobi leNo() (


Lara Technologies

080-41310124

public void setEduc(String educ) {


this-educ = educ;

1.

public String getDesignation0 {


return designation;

1
public void setDesignation(String designation) (
this-designation = designation;

public String -getAddress() (


return address;

public ,void-setAddress(String address) (


this-address = address;

-~ser.hbm.xmi
7

<?xrnl version=" 1.0" encoding=llUTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibemate/Hibemate Mapping DTD 3.0//EN1'
11http://hibemate.sourceforge.net/hibemate-mapping-3
.O.dtdl'>

<property name=ll~~erFirstName"
colurnn="USER FIRST-NAMEn!>
<property name="userLastNarne" column="^^^^-LAST-NAMEu/>
<propeAy name="userAgeVcolumn="USER AGE'/>
<property name="userEmail" c o l u r n n = " ~ ~EMAILnA
~k
<property name="userMobileNo" column="^^^^-MOBILE-NO"/>

Lara Techno:ogies

080-41310124

62

<?xml version=" 1 .Or' encoding="UTF-8"?>


<!DOCTYPE hibemate-mapping PUBLIC
"-//Hibemate/Hibernate MBpping DTD 3 .O//EN1'
"http://hibernate.sourceforge.net/hibemate-mapping-3 .O.dtdW>

< n.,,t ~ n
- -~-r,ngme="':GSer
tv "i
..:.

0 l ..u .m n = " "/>


~ ~ ~ ~
< p i o p , e name="
~
iduc $ o ] u f i :EDUC
=~~
"/> . ~ ~ ~ ~
<p;op&rtyname="
.
design& on ' < C b i u m n = ' ' . ~DESlGNATION"h.
~~~.
- "...'
<propert@arne=" address " c o l u m r i = "-~ADDRESS1'b
~~~
-----a

,:.

::

. .

. ..
,?...

,.
:
:'
....

...
.:I,.'

....

<on-to-one'ndme="user"
.. .
c~ass="com.lara.user"constrained="tmel'!>
.

Manager.iava

i:

package com.1ara;

import org.i~ibernate.Session;
import org.hibemate.SesslonFactory;
import org.hibernate.cfg.Configuration;
public class Manager
{
E a r a Technologies

080-41310124

public static void main(String[] args)


{
User user = new User();
user.setUserId("index101");
user.setUserAge(23);

user.setUserEmail("manikanta@gmail.com");

user.setUserFirstName("MANIKANTA");
user.setUserLastNarne("CH0UDHARY");
user.setUserMobileNo("9986340298");
UserDetails ud = neiv UserDetailsO;
ud.setAddress( "TPT");

ud.setDesignation("PM");
ud.setEduc("BTechl');
ud.setUser(user);
user. setUserDetails(ud);
iS'vn5g~irajionconfig = new Configuration();
config.configufe(); ;
.:.
..

"!

. ,

:
;

SessionFactory sf = ~ - c o n f i g $ ~ i l d ~ i s. .s. ~ a c t o r y O ;
Session session = sf.open~ession();
.

. .

Foreign key d e v e l o ~ m e n
t:

Lara Techiloiogies

680-41310124

. .

Usually foreign key is used for to join the two tables In this example we
want to join User and UserDetails. In this we are using one-to-one join if one
modification is done in one table then that modifications will reflect back
to another table also.

narn e: The name of the property.


class (optional - defaults.to the property type determined by reflection): The
name of the
associated class.
.
.

... ..

cascade (optional) specifies which operations should be cascaded from the


parent object to the associated object.

::.r..j.::;.,

i;i:-Po-ma;ly,js us,& for in one table one column is.referring to multiple


. . . . table
columns in theother
in:.this eg;BATCHES
,..
table BATCH- ID. is refered by so many columns fiorn
:ih$ ;STUDENTS
T@LE
.
;.

: .

:.;.. .. . .
..,'.- .. :
.':,
.. . ....
...

.;
....*,...i. '

hi bernate.cfp.xml,
: >; '
....
.:
.
;:.-;. ,*.,:, . . .
.. ... ..:
<?xrnl ve&on=l.1;.01 en~od~r1utf-8t?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernaie/Hibemate cohfigurltion DTD 3.O//EN"
"h~p:/hibemate.~,~urceforge.net/hib~ate-configuration-3.~.dtd~t~
, . ,.
..
?

<

'

...
. .

'

<!--

at abase connection settings -->

<property name="co~lnection.driver class">


oracle.jdbc.driver~racle~river</~ro~ert~>
<property name="co~!nection.url">
kara Technologies

080-41310124

<!-- JDBC connection pool (use the built-in) -->


<pi-opei-tyname="~onnection.pool-sizen>l </property>

<!-- SQL dialect -->


<property na1ne="dialectn>

org.hibernate.dialect.OracleDialect</property>
<I-- Enable Hibernate's automatic session context management -->
<property name="curent-session-context-classl'>thrzad</property>
<!-- Disable the second-level cache -->

<property name="cache.pr~~irle~-c!~!:s">
org.hibemate.cache.~o~ache~rovide~/prope~~
<!-- Echo all executed SQL to stdout -->
(property name="sho& -sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

package com.lara;
public class Student
{
private Integer id;
Lara Technologies

private String firstName;


private String IastName;
private Integer age;
private Batch batch;
public lnteger getld() (
return id;

public void setId(1nteger id) {


this-id = id;
1

public String getFirstName() {


return firstName;
)
public void setFirstName(String firstName) (
this:first~ame= firstName;

public String getLastNarne() {


return IastNarne;

public void setLastName(String 1astName) (


tbis.lastName = lastblame;

public Integer getAge() {


return age;

pu btic void setAge(1nteger age) {


tbis.age = age;

public Batch getBatch() {


return batch;

public void setBatch(Batch batch) (


this.batch = batch;
1

Batch-iava
package com.lara;

Lara Technologies

import jma.util.HashSet;
import java.util.Set;
public class Batch
private Integer id;
private -StringbatchName;
private Set students = new Hashset();
public Integer getId() {
return id;

.I
public void setId(1nteger id) {
this-id = id;

1
public String get.atchb!me() (
return batchName;

public void setBatchName(String batchName) {

public Set getstudents0 {


return students;

public void setStudents(Set students) {


this-students = students;

public void;add~tudent~o~atch(~t~dent
std)

ff(students -- null)

1-

students = new Hashset();

students.add(std);

Lara Technologies

import java.uti1.Tterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg:Configuration;
public class Manager
{
public static void main(String[] args)
{
Batch batch = new Batch();
batch.setId(3);
b~tch.set~atch~arne(~~~~~AI~2~~");
Strrdefit std: = nevi' Student();
std 1.setFirstName("MANI");
std 1 .setLastName("LARA");
stdl setAge(23);
stdl .seBatch(batch);
batch.addStudentToBatch(std 1);
Student std2 = new Student();
std2.setFirstName("RAMUM);
std2.set'~astName("~~~~~1);
std2.setAge(23);
std2.setBatch(batch);
batch.addStudentToBatch(std2);
'

Configuration config = new Configuration():


config.configure();

i a r a Technologies

Session session = sf.openSession();

//Randomly
.
. . .
UPDATE.

/*

..

.&:Batchbatch =(l3at~h)se~sion.load(~atch.class,3);
;,Iteratori t = batch.getStudents().iterator();
Stbdent std = null;
if(&has~ext())
*
.
{
std =.,(Student) itsnext();

;:

..

s t d . s e t ~ i r s t ~ a m e ( ' ! ,MANJKANTA");
C~'~~~

s,ession.saveOrUpdate(stdj;
..
se,~sion.~et~ransaction().commit();
. ...
* I . ; ..
.

. .

. . ..,

..: .. .....

//PARTICULAR
..
RECORD UPDATE

<;

.,

I*

..

.
.

.: . .>-Batchzbatch
=

(~atch)session.load(~atch.class,3);
i ~ t e r ~it=b;tch.get~tudents().iterator();
or
std = null;. .
.
whilk(itha~~ext()) :
.

t
std ='(Student)it.next();
if(std.getId() =2)

C
break;

1
1

std.setFirstName("CHANGEDAGAIN MANIKANTA");
session.saveOi-Update(std);
Lara Technologies

080-41310124

71

//UPDATE WITH OUT BATCH


/*
Student std = (Student)session.load(Student .class,I j;
std.setFirstNarne("NEW-CHOUDHARY
");
session.saveOrUpdate(std);
*/
//READING THE RECORDS FROM TABLE
List batches = (List)session.createCriteria(Batch.class).list();
Batch batch = null;
Student std = null;
Iterator it = null;
for(int i=O;i<batches.size();i++)
{
batch = (Batch)dzitches.get(i);
it=batch.getStudents().iterator();
.whiIe(it.hasNext()).
. ..
.

:. .

std = (Student)it.next();

session. flush();
session.close();
1

"

!/DELETEING'THE Record From T B L E


/*
Batch batch = (Batch) session.load(Batch.class, 3);
Student std = null;
Iterator it = batch.getStudents().iterator();
while(it.has~ext())

Lars Technologies

080-41310124

72

std = (Student)it.next();
if(std.getId() =2)
break;

batch.getStudents~.remove(std);

I .(c) many-to-manv deveIopment:


.

..

hibernate.cfp.xml

.
.
,

'..:

12

,...

<--.~
.

..

..

,.<?xm]version='i:~~~~nc,9ding='utf-8'?>
<,;', :< ,:;
:<!DOCTYPE hibem'kte-Sonfiguration
PUBLIC
:>.+ : Y
I)-//Hibemate/'Hibehate Configui-ation DTD 3. O//EN"
"htt~:/mibemate.sourceforge.net/hibemate-configuration-3.0~dtdt1~

!....
. C.. ..>,.-;,. ".-:
.. ::.. +
:
.
.
: ..:
' ;

..

..T

. .,

.:<
.;!

<!-- Database connection settings -->

<p~o~$rty;n~e=i!connection.driver
. .
-classn>
...
. . .
om
.m
ysql
.jd
bc,Driver</property>
. ..: .:..:.;.e:
<property n&e="cohnection.url">
,..,.. : . .
~ : ~ j d b ~ : r n ~ ~ ~ l / l o c .ara</property>
alhostn
<property n a r n e = ~ ~ e c t i o n . u ~ ~ r n ~ e ~ ~ ~ r o o t < / ~ r o ~ e r t ~ ~
<property name='i~~nnection.passwo~d"~~/property>
...

'

. .. .
, ..i,'C,..

'...

.,...

..

<!-- JGBC comection pool (use the built-in) -->


<property name=ttconnection.pool~size">
1 </propep>
<!-- S Q dialect
~
-->

<property name="dialectn>
org.hibemate.dialect.MySQLDialect</property>

Lara Technologies

<!-- Enable Hibernate's automatic session context management -->


<property name="current-session-context-class">thread</property>
<!--Disable the second-level cache -->
<property name="cache.provider-classv>

org.hibernate.cache.NoCacheP~-ovider
clproperty>
<!-- Echo all executed SQL to stdout -->
<property name="show-sql">true<lproperty>
<!-- Drop and re-create the database schema on startup -->
<property name="hbrn2ddl.auto">update</property>

<mapping~resource="com/lara/Batch.hbm.xm1"/>
<mapping resource="com/lara~Student.hhm .xm! "!>

package com.!ara;,

import java.utiI.HashSet;
import java.util.Set;
public class Student

i
private Integer id;
private String stdName;
yri-vat'e String stdQualification;
private Set batch = new Hashset();

public Integer getId() (


return id;
1

public void setId(1nteger id) (


Lara Technologies

080-4131 0124

. .

..

this-id = id;
1

public String getStdName(j {


return stdName;

public void setCtdName(String stdHame) (


this.stdName = stdName;

public String getStdQualification() (


return stdQualification;
pu blicvoid setStdQualification(String stdQualification) (
this.stdQua1ification = stdQualification;
1

public Set getBatch() {


return batch;
.

.
I>

.
-.

public void set~atch(setbatch) (


this-batch = batch;
} . . ;

.;

+.. .: . ..

. ..
. . .. . ,..
. .
.

package corn-lara;
import j ava.util.Date;
import java.uti1 .Hashset;
import java.uti1.Set;
public class Batch
private Integer id;
private String batcMaine;
private Date startDate;
pri;ate Integer duration;
private Integer fee;
private Set participents = new Hashset();

Lara Technologies

080-41310124

public Integer getid() {


return id;

1
public void setld(1nteger id) {
this-id = id;

public String getBatchName() (


return batchName;

public void setBatchName(String batchName) {


this.batchName = batchName;

public Date getStartDate() (


return startDate;

public void setStartDate(Date startllate) {


this-startDate = startDate;

public Integer getDuration() (


return duration;

public void setDurati on(1nteger duration) (


this-duration = duration:

public Integer getFee() {


return fee;

public void setFee(1nteger fee) (


this.fee = fee;

public Set getParticipents() (


return participents J

public vbid setParticipents(Set participents) (


this.participents = participents;

1
public void addParticipentsToBatch(Student std)
{
pal-ticipents.add(std);
std.getBatch().add(this);
Lara Technologies

080-11310124

I
I

public void removeParticipentsFromBatch~Studentstd)

t
participents.remove(std);
std.getE3atch().remove(this);

<?xm1 version=" 1 .On encoding="UTF-8"?>


<! DOCTYPE hibemate-mapping PUBLIC
"-//Hibernate/Hibemate Mapping DTD 3.O//ENW
"http:/kibemate.sourceforge.net/hibemate-mapping-3.O.dtd">

<property name="stdNameWcolumn="STUDENT-NAMEw/>
<property name+"'tdQualification" column=
"BATCH-QUALIFICATION"/>
,

<set n&ne=?batch" table="B-S-JOIN">


<key co1umnr"STD ID.!'/>
<many-to-many C O ~ U ~ ~ = " '. B A-TID"
C Hclass="~atch"/>
</set>
</class>
.

<?xml version=" 1.0" encoding="UTF-8"?>


<!DOCTYPE hibemate-mapping PUBLIC
"-//HibernatelHi bernate,Mapping DTD 3 .O//ENV
Lara Technologies

080-41310124

<hi bemate-mapping package="com .lara">

<set name="participents" table="B -S-JOIN" inverse="trus">


<key column="BATCH-ID"/>
<many-to-many column="STD -ID" class="Student"/>
//--a\
Y
L-'

at

package com.lara;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import org.hiber-nate.Session;
import '6rg.hibernate.SessionFactory;
import org.hibe!nate.cfg.Configuration;
public class Manager
public static void main(String args[])

,l

//add();
llreadBatchWiseStudents(3);
i/LipdateParticularStudent(3,102,"Changed MAMKANTA");
dele1ingRecord(4,104);
\

private static v ~ i da d d o

i
Batch bl =new ~ a t c h ( ) ;
bl .setId(3);
bl .setBatchName("REGULAR JAVA");
bl setDuration(l20);
bl .setFee(5000);
Date date = new Date();
Date startDay = new Date(date.getTime() +
7*24*60*60* 1000);
b 1-setStartDate(startDay);
Batch b2 = new Batch();
-b2.setId(4);
b2.~etBatchName("SI;Rr?u'Ci");
b2.setDuration(3 0);
b2.setFee(l000);
Date SpringstartDay = new Date(date.getTime0 +
10*24*60*60* 1000);
b2.setStartDate(SpringstartDay);
Student std = new Student();
std.setId(l0 1);

std.setStdName("RAMESH1');
std.setStdQualjfjcation('~B.Tech");
b 1.addParticipentsToBatch(std);
b3.addParticipentsToBatch(std);

Student std! = new Student!);


std 1.setid(] 02);
stdl .setStdName("MANIKANTAtl);
std 1 .setStdQ~alification(~'B.Tech");
b1 .addParticipentsToBatch(std 1);

Lara Technologies

050-41310124

Student std2 = new student();


stdZ.setId(l03);
std2.setStdName("NAGESHn);
std2.setStdQualification("B.Tech");
bl .addParticipentsToBatch(std2);
Student std3 = new Student();
st& .setld(l04);
std3.setStdName("RAMU1');
std3.setStdQualification("Bsc");
b2.addParticipentsToBatch(std3);

SessionFactory sf = getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(b1);
session.save(b2);
session.save(std);
session.save(stdl);
session.save(std2);
session.save(std3);
session.getT1-ansaction().cornmit();
sessiofi.flush();
sessjon.close();

. .>
....
. .. .,..

.:

private static SessionFactory~getSessionFactory()


Configuration config = new Configuration();
config.conf;,gure();
Sessio~.Factcrysf = config.buiidSessionFactor?;(;b;
r e t w n s$

1
private static void readBatchWiseStudents(int i)
SessionFactory sf = getSessionFactory();
Session session = sf.openSession();
session.beginTi*ansaction();

.
.

.
..,

....
,.. .

..

,.
:-

Batch b = (Batch)session.load(Batch.class, i);


Set students = b.getParticipents0;
Iterator aljStudents = students.iterator();
Student std = null;

while(allStudents.hasNext())
std = (Student)allStudents.next();
System.out.println(std.getld()+":"+std.getStdName());

private static void UpdateParticularStudent(int batchNo,int

t::

.
....

~ e s s i o n ~ a & o r y s getSessionFactory();
f=
Session session=j.sf.open~tssion~;
..
session.SeginTiznsa~'iion(?;
~,etqh.
..:
........ batch = (Batch)session.lo~d(Batch.dlass,batchNo);
Iterator<;it= batch.get~artici~ents().iterat&.,-: :
Studkptlstd = null;
while(it:hasNeat())
.
{
a,..;

'i..

Lara Technologies

080-4131 0124

private static void deletingRecord(int batkhio,int studentNo)


{
SessionFactory sf = gctSessionFactory();
Session session = sf-opensessionj);
session.beginTransaction();
Batch batch = (Batch)session.load(Batch.class, batchNo);
Student std = null;
Iterator it = batch.getPai-ticipents().iterator();
while(i t.hasNext())
{
std = (Student)it.next();
if(std.getId() =studentNo)
break;

batch.getParticipents().remove(std);

Example: programaticllydeclaring properties


Developing an application without configuration file. Keeping inside ur
client program by creating config object.
Create one application and update the buildpath with relavent JAR files.

Now create a package structure and develop a Pojo object.


We want to crzte table for Person with column names as
(Person-ID, PERSONNAME, PERSON-AGE).So first develop one Pojo
class with all these attributes
package com.lara;
public class Person

Lara Technologies

{'

private Integer id;


private String personName;
private Integer personAge;
public int getIdO {
return id;

public void setId(int id) (


this-id = id;

public String getPersonName0 (


. .
...
return personName;
..I:.:
J:
pu.blic
.....
void setPersonName(String personName) (
this.personName = personNarne ;

'1.

. .. .... ..

Now d&$lop
. .
one hb&
. . . . . . file for every Pojo:class in one package.
.. . . . . .
. . .<.
.
,.
.,
i.:.:,<:t
".
::?
' :;:.......
:
:
;
In hiFe6ate
.--.
....... w ~ t h ; o uprimary
t
key we can't develop any table.
. . . .
.,; ,.. :.:.
In hbrnfil6;we
:,.
wait totake care about all attributes for creating table.
In person??iiblewe want.&omake
...
PERSON-ID column as
autoincrerneni:.:&d
.... primaryliey ..:thenuse id and generator tags.
.......
..: .

. . . . .

iy,:,

.,

:,.I..

:,r< , .
'

.
:

. ..

. . ..,.

<?xml version=" 1.OH?> . . . . . . . .


<!DOCTYPE hibernate-maPpin'&~UB~1~
..:
.
"-i'IHibemateMibernate Mipping DTD 3.O//EN"
"http:/hibemate.sourceforg~.n.et/hibernat-mapping-3
..
.
.O.dtd:'>
.

<hibernate-mapping>

Lara Technologies

.,

080-41310124

... ...

..

,c.::>.

Now developgne
.
dl~entpro,oramm
.

. .
.. . .

package.
. com.lara;
.

1.

..

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hib.e&,ate.cfg.~cnfiguration;
. .
. . ..

..

..
..

public,class Minager (
:.:publicstatic void main(String [1args).
.{
. .
.. .; .:.:;Rerson p 1
new p&on ();
' & j s e t ~ e r s o n ~ a m("RAMESH");
e
. ...
p ~: i;. s e t ~ e r s o n ~(29);
ge
.

..

..,

. .

..

, ,.

.. . .. . ..
.i. . '.

.
,

.
.

..

Configxation config = new Configuration ();


~onfig~set~roperty("connection.3ri~er~class'~,
.
~"oraclejdbc.driver~O~ac1eDriver");
c.onfig.set~roperty("connection.url
..
",
"jdbc:oracle: thin:@localhost: 152 1:XE");
config.setProperty("connection.username ", "system");
config.setProperty("connection.password ","great 123");
config.setProperty("connection.pool~ize","1 ");
config.setProperty("dialec",
''org.hibernate.dia1ect.0rac1eDia1ect7');
config.setProperty~:'!.currentsession-context-class ",
"thread");
config.set~roperty("cache.provideLclass ",
"org.hibemate.cache.NoCacheProvider");
..,

.-.

i a r a Technologies

config.setProperty("sho;v sql ","true");


~onfi~.set~ro~ert~(~~hbm2ddl.auio
","update");

config.add~esource("com/larai~erson.hbrn~xm1~~);
System.out.println("Hibernate got configured.");

s SessionFactory sf = config.buildSessionFactory 0;
System.out.printIn("SessionFactory got configured.");
Session session = sf.openSession ();
System.out.println("session object got configured.");

session.beginTransaction 0;
System.o~t.prjntln("transaction started..");

. . . .

. .>,
. ..: . .. I. .. ...
:
.-; . .<. .<,.,
. ::
. . .. y,<.*..

.- ;..

-:&

s,.

....

n...

4;:
.;.

F.l.G
.

*I;.,

%.
y~

.......

:....

.,

-;
. .

..?

5 . I

. .. ...... .

. . .-.
;;
.
.

--.

...
-.

.
.....
. . ..

..

,
.:

: ..,.,... .....:.. ..
... > .. .::
v, ..::
:. .
.:.
. . ,..

. .
. . . . . .

. ..
.... :.

....:
';;!,&.
, ..

....

,.-:*
":.".
.:?;?*;

.,

..: ;<:;:;:.;,
. .

..-. .. . . .. ..

..:.
*..
. .... ...5:. .:,'
.
2::

..

,,.

i .

~.:?
; :.;z. ,:..;.."":
,,:.. .>:.:,
.<;.
.. . .. ... .. . ..

..:':$..-.

. ,: . ; .
.. . ..
-..-. . .
:,

: ':

:
:

sessi,on.get~ran~acti~n~~O,cornmit
0;
System.out.println(~transactioncommitted..");
.sess~n.flush0;
System-out-println("session got flushed..");
~.~ess~on.close
...
..
0;
:S~stem.~ut.println(~~session
. . .
got closed..");
/;.!

'

',

. ..

,.. .. . . . .'.. . .
.

Now start the datab&i(i.e


.,r'.... . . Oracle) and run the program.

Example2 programatidlydeclaring properties

Lara Technologies

080-41310124

create a package structure and d e ~ e l o pa Pojo object.


package corn-lara;
public class Person
(
private String orderId;
private String orderName;
private Date orderDate;
private String orderDescription;
private Double orderprice;
private String orderB3;;
public Stnong getOrderId0 (
return orderId;
1

public void setOrderId(int orderId) (


this. orderId= orderld;

public String getOrderNarne0 (


return orderName;

>

public void setOrderName (String orderName) (

public, Date getOrderDate() (

public void setOrderDate(Date orderDate) {


this.orderDate= orderDate;

public Striong get@rderDescription(:! (


return orderDescription;

public void setOrderDescription(int orderDescription) (


tFiis.orderDescription = orderDescription;

public Double getorderprice() (


return orderprice;

;!
Lara Technologies

080-413!0i24

htt p:!/j~vaeasq.toal!.cdsnt

public void set01-derPrice(intorderPrice) {


this. orderPrice = orderPrice;
I

public String getOrderBy0 f


return orderBy;

public void setordel-By(StringorderBy) f


this-orderBy= orderBy;

1
&w develop one hbrn file for every Pojo class in one package.
<?xrnl version=" 1.OH?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibematemibemate Mapping DTD 3 .O//ENM
"http:/hibernate.sourceforge.net/hibernate-mapping.C.d:dn,

<hibernate-mappi ng>

Now develop one client programm

2.3' .

package corn-lara;
Lara Technologies

080-41310124

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibemate.cfg.Configuration;
public class Manager {
public static void main (String [I args)

Order order= new Order();


Order.setOredrld("ord 101");
Order.setOredrName("TV");
Order.setOredrDate(new Date());
Order.setOredrDescription("Sony W");
Order.setOredrPeice(12000.00);
0rder.setOredrBy("LARA");

Configuration config = new Configuration ();


config.setProperty("connection.driver class",
"oracle.jdbc.driver~0racle~river");
config.set~roperty("conne~tion.url
",
"jdbc:orac2e:thin:@localhost: 1521:XE");
config.setPro~erty("connection.username", "system");
config.setProperty("connection.password ","great 123");
c~nfig.setProperty("connection.~ool
-size ","1 ");
config.setProperty("dialec",
"org.hibernate.dialect.0racleDialect7');
~onfig.setProperty('~current
session-context-class ",
"thread");
config.setProperty("cache.provider -class ",
"org.hibernate.cache.NoCacheProvider~
~onfig.setPropert-~['~show
sq1 ","true" j;
config.setProperty("hbm2ddl .auto ",'*updaten); .
config.addResource("corn/lara/Person.l~bm.~mJ~~);
System.out.printJn("Hibemate got configured.");

SessionFactory sf = config.bui1dSessionFactory 0;
System.out.println("SessionFactory got configured.");

Lara Technologies

Session session = sfopenSession 0;


System.out.printlr,("session object sot configured,.");
session.beginTransaction 0;
System.out.println("transactioi~ started..");

session.save(order);
System.out.println("person object saved.");

session.getTransaction ().commit ();


System.out.println("transaction committed..");
~, .

.
.

.
'

..

sesision.flush 0;
~~stern.out.~rintln("session
got flushed..");
..: . sessi.on.close
...
();
~~stem..out.~rjntln("session
. ...
got closed..");

..

1
J

:. .

.
. .;..

. . . ..
.

.
.

..

. ,

// To readbll
, .., .(.(
the records
, . .
,.
I*
~ i s t < ~ r d e r > v=
: l session.create~rit~ria(com.lara.~rser.class).list();
~~t
for(0rder order::
.
. list)
.. .
.:.
. . , ..
:{.
~~st~~.o~~~~ntIn(order.~et~rder~d());
. , . . .:,
Sysie,m:.o~t
....
.&ntln(orderfgetOrder~ame());
. .

. .

I.

Sy~tem.~ut.println(oi-deiigetOrderDzite());
_ . . .
~~stem'.out.~ri~~tln(orde~~~~t0rder~escri~tion());
~~stem.out.~~intln(order.~et0~der~rice());
~~stem.out.~rintln(order.~et~rder~~())~
.

...

... .

(OR)
.
Criteria ctr = session.createCriteria~com.larz.Order.class);
~ i r . a d d ( ~ e s ctions.eq("or&~y\
tri
abc));
.
..
..
iist-&rdei>
..
For(0rder order : list)
{
System.out.println(order.getOrderId());
..

.
. . . .
.. ...
.',3 .

Lara Technologies

080-41310124

//same can be achieved through query


/*
Criteria ctr = session.createCriteria(com.lara.Order.class);

Ctr.add(Restrictions.sq1Restriction("orderDescption7,1ike "%h%"
abc));
Query query=session.createQuery("fiom com.lara.Order");
List<Order> list = query.list();
For(0rder order : list)
{

System.out.println(order.getOrder~d()j;
System.out.println(order.getOrderName());
System.out.println(order.getOrderDate());
System.out.println(order.get~rder~escription());
System.out.println(order.getOrderPrice());
System.out.println(order.getOrderBy());

Now start the database (i.e 0racle):and run the program.

when youi- sessionFactory object is createdthen only the table scherna


is creating~jgenerating.,
Immderial of calling configure by java program/xml file by the time
of sessionFactory object creation time all the database related schemas
are generating.
Eventhough you triggered 4 times the update query on the same
transaction only once is updates the query before c0mmited.b~this we
can save the network traffic.

For the same transaction one object is keep on changing,it is calling


updateQuery before commiting.
While in the czse of s a ~ ~ e itf )is
, keep on callingistoring in the
database-where as in the case of saveOrljpdate(),it is storing the
object state in the cachi and it is called as first-level cachi.
First-level-cachi is limited to transaction (when ever transaction is
goingto commit then cachi is called.)
It is possible to keep more than one transaction in the same session.
In one transaction we caa keep as many database transactions as we
wish. Cachi is not available for the other transactions which is limited
to one transaction.
First-level-cahi is automatic one.

Polvmorphic mappings:
They are three types ofpolymorphi
:c-mappings.
...
.! :: 1. One table per class.hierarchy.
.
2. One table per subclass.
3. One table per concrete class.
.

. .

- .

'.

..

..

'

:I) One table per class hierarchy:


In thiswe will not create table for every Pojoclass we will
create table only for::superclass and all sub class attributes will present in the
same table.
hi bernate.cfg.xm1

<?xrnl version=' I -0' encoding='utf-8%


<!DOCTY?E hi bernate-configuration PUBLIC
"-//Hibematemibemate Configuration DTD 3 .O//ENU
"http://hiberfiate.sourceforge.net/hibemae-cnfiguration-3.0.dtd">
<hibernzte-configuration>
<sessioi~-factory>
<!-- Database connection settings -->
<property
name="connection.driver -class">com.mysql.jdbc.Driver</property>

Lara Technologies

<property
name="connection.url11~jdbc:mysql:!/localhost/lara~/property>
<property name="connection.userriame">root<lproperty~
<property name="connsction.password''></property>
<!-- JDBC connection pool (use the built-in) -->

<property name="connection.pool- size1'>


.
l</property>
<!-- SQL dialect -->
<property
name="dialectt~>org.hibemate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->


name="current-session-context-classn>thread</property>
<!-- Disable the second-level cache -->

<property
~~me="cache.provider~c1ass">org.hibernate.cache.NoCacheProvide~/prope

*Y>
<!-- Echo all executed SQL to stdout -->

<property name="show-sqlV>true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto1'>update</property>

package com3ara;

public class Person

private int id;


private String firstName;

public int getId() (


return id;

public vaid setId(int id) (


thisid = id;

public String getFirstName() {


return firstName;

public void setFirstName(String firstName) (


this-firstName = firstName;

1
.

'

...

pa.ckage com.lare:;';:.
. . . . . . . ..
,.. ..
,

.--

.-

.
. . ....

.. ..

:>~.l
.>.
..&

. ..... . . . . .. . ...
.

p ? i h ! i.~ ; r...:..! Emnlovee.


. ~ ~ - extdnds
Person
.

..

.
..

.:

priva(e:String
empNo;
:..

. . .

. . . .:.
.

.
.. . .. .
. ..: . !*'
. ,
.. 2 .: '.'

'?

. . .

:'>.
'"-.. '2:.
.,.

public st&&
. . . g. k t ~ m p ~ o (
()
retu..........
~:n,g.empNo;

..: ;. 1...
.
.

.:.

.::.

.
,

'

.;.
... ,

. .

. ..,.; .

:i

.
... .

.. .... ..

,.

.. .. .. .. ..

p u ....
b-VI::..y4t
~ ~ c ~ ~..r;o i .d .~ s ~ t ~ m pempNo)
~ o ( ~ t(r i n g
..
..; :;-.:;.-'~~~thlsse~'pN~.:=-:&mpNo;
I;.,;. .: ;.
.
s.~.!.~

1:

. . .

:,,.;5:,

;,.

.. .

......F.
.
'..., ,. .
... .

_ _ .:

,. .
.

. . .:

:.\

. :

.
. ,:

.".

..

PermanentEmp10vee.iava:~

package corn.lai-a;
public class
-,.
PemanentEmployee extends Employee

C
private Double allowances;

public Double getAllowances() (


return allowances;

public void set~llow&ces@oubleallowances) {


th is.allowances := allowances;

<?xinl version=" 1-0" encoding="UTF-8"?>


<!DOCTYPE hi bemate-mapping PUBLIC
"-//Hibernate/Hibemate Mapping DTD 3.0//ENM
"http://hibernate.sourceforge.net/hibemate-mappng-3.O.dtd">

<id name='lidVcolumn="PERSON-ID">
<generator class="native"/>
<!id>
<property name="firstNarne" column="PERSON-FIRST-NAME"/>
<discriminator column="P -TYPE type="string"l~
<subclass name="EmpioyeeWdiscriminator-value="e">
<property name="empNon column="ENG-NO";>
<!subcIas+
<subclass name="PermanentEmployee" discridnator-value="pen>
<property name="allowances" column="ALLOWANCES'~>
<subc!ass>
</ciass>
</hibernate-mapping>
*

package com.lara;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
public class Manager
public static void main(String[J args)

,.

PermanentEmployee pe ,=new PermanentEmployee();


pe.setld(l);
pe.setAllowances(50000.00);

Configurati,on config = new Configuration();


config.configure0;
.Ses'sionFactorysf = config.buildSessionFactory();
~&sionsession = sfApen~ession();
s~~sion.be~in~ransaction();
........
session.save@e);
session.getTransaction~.commit();
.
session.flush();'
- session.close()5:
..,.?.!-

':'

-,

...

.. .. . .. .

2) One table p~r~subclass:


.

For every subclass there is one table


. e
. x a .:.
~ l e.<
...~ ~
the
d Person.hbrnixrn1
~t:~h~
In a b o v .e. ..~_...
....
:...
i.:.

...
.,.....
<.-.'
. ,... ;...-;i. ::
: .
. !:::;......:>-,?>
.:.. -......-;<k..!;...
<,>:..:, ;. .-.-;> :. ..
). :,, ?
:$
!:.;
.!
L...
;:.. . .
'., ,.....
: . :
..
.. .
:,
.. .. ........
.
.
.
.
,. .
..
.,;..I

&
.

. i

P e r s ~ ~ . h b ~ . ~ a ] ' : ; ; : -.

. ... .

<?xml version=" 1.0" encoding="UTF-%"?>


<!DOCTYPE hibemate-mapping PUBLIC
"-//Hi bernate/Hi bernate Mapping DTD 3 .0NEN1'
"http:!/hibernate.sourceforge.net/hi hernate-mappi fig-3 .O.dtdl'>
I

<hi bernate-mapping package="com.lara">


a

<class name=l'Per~~nll
table="PERSONS">
<id na.me="idUcolumn="PERSON -ID1'>
<generator class="native"/>
Lara Technologies

080-41310124

<jid>
<property name="firstName" column="PERSON FIRST-NAh4E"/>
<joined-subclass name="Employee" table="P-E";
<key column="id"/>
<property name="empNoVcolumn="EMP-NO"/>
</joined-subclass>
<joined-subclass name="PermanentEmployee1'table="P-PEW>
<key column="id"b
<property name="allowances"
co!umn="PERMANENTEMP-ALLOWANCESv/>
</joined-subclass>
</class>
</hibernate-mapping>
3)One table per concrete class:

In this develop tablefor every pojo class as we used earlier.

Examplefor Query in terfaee:

<?xml version='l.O' encoding='utf-8'?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibematem bernate Configuration DTD 3 .O/ENn
"http://hibernate.sourceforge.net/hibeinate-configuration-3 .O.dtdV>

<!-- Darabase connectior, settings -->

<property
name="connection.driver -class">com.mysql.jdbc.Driver</Froper~
<property
name="connection.ur1">jdbc:mysql://localhost~lara</propert~>
<property name="connection.usernarne1'~root</property>
<property name="connection.password~/property>
<!-- JOBC connectior? pool (use the built-in) -->

<!-- SQL dialect -->


<p:zperty
name="diaIect">org.hibernate.dialect.MySQLDialect4prope~y~
<!--Enable Hibernate's automatic session context management -->

<property name="current~session~context~class">thread</property>
<!-- Disable the second-level cache -->

<property
name="cach~.provider-class">org.hibernate.cache.NoCacheProvide~/prope
...
rtY'
.
.

..

<!-- Echo.'all executed SQL to stdout -->


<property name="show-sql ">true</property>
. ,

<!-- Drop andre-createthe database schema on startup -->


<pxyerty carne=11hbm2ddl.autol'>~pdate</~ro~erty>
.

..,
. . . . . . .
... ,.,...
;,.:
,:..,,... ,
>
:..: .....
.....
.

.
. :..
. .
. .

...

. . . .. .

...

....:..
..',?-

. .,
.lC._i..

'

. . .
.
.

. . .

..

</session-factory>
. . ,.
.

..

....

. . .

....

<mapping
.. ,. r.esource="com/i ~ r a / ~ ~ ~ ~ . o n . h b r n . x m i ~ ~ / >
. . .
.....
........
.

..

-.

..

.:.. ..

package corn.1ara;
put!ic class Person
{
private String id;
private String firstName;
privatestring IastName;
private Integer personAge;
Lara Technologies

080-41310124

public String getId() (


return id;

public void setld(string id) {


this-jd = id;

public String getFirstName0 {


return firstName;

pu biic void setFirstName(String firstName) (


this.firstName = firstName;

public String getLastNarne0 {


return IastName;

public void setLastName(String lastblame) (


inis.iastName = IastName;

public Integer getPersonAge() (


return personAge;

public void setPersonAge(1nteger personAge) {


this-personAge = personAge;

1
Person.hbm.xm1
<?xml version=" 1 .O''?>
<!DOCTY?E hibemate-mapping PUBLIC
"-//Hi be~xateiliibernateMapping DTD 3 .O//ENW
"http:/hi b e m a t e . s o u r c . ~ f o r g e . n e t / h i.O.dtd
b ~ ">

Lara Technologies

080-41310124

(property narne="firstNameMcolumn="PERSON FIRST NAMEn/>


<property name="lastName" colurnn="PERSON LAST-%AME~~/>
<property name="personAgenc o l u m p = " ~ ~ -~AGEw/>
~0G
</class>

import java.util;List;.:-. ..
...

import org.hibemate.Quer-y;
import org.hibemate.Session;
import org.hibernate.SessionFactory;
import org.hibeinate.cfg.Configuration;
public class Manager(
public static void main(String[] args)

!
/*
Person
pl
. .. ....
.
*.

. .
.,...

= new Person(j;

config = new Configuration();


.&nfigur~tj.on
. ..
.
&nfig;configu.re();
.
. . .
SessionFactor=s f = config.buildSessionFactory();
Session s.ession = sf.openSession0;
session.begin~ransaction();
.I

.
1
_

Ouery query = sessior~.cr~ateQue~("frorn


com.lzra.Person");
List<Person> !ist = query.!ist();
for(Person p:!istj
{

Lara Technologies

080-41310124

99

How to make composite primaryKey:

If we want to make two attributes as primary key field then create separate
class for two attributes and that class should implement Serialization and
override equals() and hashcode().

EG:
hi bernate.cfe.xm1
<?xrnl version='l.O1 encoding='utf-8'?>
<!DOCTYPE hi bemate-configuration PUBLIC
"-llHibemateMibernate Configuration DTD 3.O//ENV
"http://hibernate.sourceforge.ne~ibemate-confi~ura~ion-3
.O.dtdV>

<!-- Database connection settings -->

<property name="connection.driver classw>


oracle.jdbc.driver&-acle~iiver-4~ropert
<property name="connection.url ">
jdbc:oracle:thin:@,Iocalhost: 152 1:=</property>
<property name="connection.username">systemc/prope .
<prope'hy name="connection.password">great1 23 </property>
<!-- JDBC connection pool (use the .built-in)--->
<property name="connection.pool'-size"> 1</property>
<!-- SQL dialect -->

<property narne="dialect">
Lara 'Technologies

080-41310124

<!-- Enable Hibemate's automatic session context management -->


<property name="current-session context-class">thread</property>

<!-- Disable-the second-level cache -->


<property name="~ache.~rovider
-classv>

org.hibemate.cache.NoCacheProvider~iproperty>
<!-- Echoall.executed SQL to stdout -->
<property name="show-sqIn>true</property>
<!-- Drop and re-create the database schema on startup -->

<property name="hbrn2ddl.auto1'>update</property>

.
.

..

package com.lara;. .,, .,:


.
pu bli'cs@lass
x.
Person,.
.. .. ..
... : ::..
.
.?.
.. . .. . . . . ..*.
.. _ .,.
{
. . . .. .. . . .
privaf&i~mj'~ld:~p~ield;;
<iz:?q:,.!
:
priva te?S?.ring
. .,
last~arhk;
.

. .

'I..

::.
.

. . . .

. .<

public PKField getPkField() (


return pkField;

public void setPkField(PKFie1d pkField) (


this.pkField = pkField;

SI

public String getLastName() (


return IastName;
Lara Technologies

080-41310124

public void setLastNarnefString lastName) (


this.lastNarne = IastName;

public Integer getPersonAge0 (


return personAge;

public void setPersonAge(1nteger personAge) {


t his.personAge = perso~4ge;

package com.lara;
import java.io.Serializable;
public class PKField implements Serializable
(
p'riva t e String id;
private String firstName;
public String getId() (
return id;

public void setId(String id) (


this-id = id;

public String getFirstNa!ne() ( .


return firstName;

public vQid setFirstName(String firstName) (


t his.firstName = f ~ s t N a m e ;

public boolean equals(0bject obj)


PKField pk = (PKFie1d)obj;
return id.equals(pk.id)&& firstNalne.equals(pk.firstName);

public int hashcode()

....
..-

...

i a r a TechnoIcgies

public class Manager


{
public static void main(Stringa args)
{
/*
,%
.
. .

...

. .

Person p 1 = new persono;


PKField pk = new PKFieldO;.
pk.setId("TNDEX102"); . ... .. . . .
pk.set~~stName~MANIV);
>, ;:, :. . ..:.
. ; p ~,~i",.;F
~
@
~
.
i
c
l
d
.( p k ) ;
. .. .
&
.!:?:
.........
,,
;.
. ~set~$i&&e(~~~'~UJ)~y
,l
).;. ';.. .'',,j
. . .... .... . . . .
,:
p 1.setPersofige(29);
.. .
*/ .

l :

.:;

'

. .

.L

?..

. '.

.>

.. .. . . .

. ,.
..:.*, .;"....
:. . . .
. ,
>.......
,.b>
.. !L!
.
.
! : i(>".
;c': Sii;q . . . . . . . . . . . >..
>
; ;&:,>~'$~.$:*>,.z. * . . <*;:;.,.: >. ,

$.$ .:. . :. .

'?.Y

,.:'~:.*:i~..rz,::,l~

,<5:j8zs>:;;2$>'>.

. .

. .;$.;:?: ., >.

>
6
.
."L
c

.,-. ..:. ...?.


. .. . ..L..
>
t
i
:
. . .
. . :.:
.
. . -.. . . .. ,. .:. ..
. : . . . . . . . .. .

...

<!..

...?.>:Y.L

. . .. 5:gF,.!

~-:-

:,.

' . ,.- :,<.


--I:-;
.:
:

. .. . ..
< .. : :

configuration
. . . . .
config = new Configuration();
confi&onfigure();

< ..

, ;,;.

<
.:.....
.i-.
...
. . .
. .. . ,
.....
* :;
.;i.q:. ...'.-.

. .,.

><
.....
.. ;. ;: :.' .

<, &

>

.:

'

. j ::.
....
4
. . .<<;,.

'

4..,.! ..?.
SessionFdetdry' sf ,=~&6i;fig.~buijd~ession~actory();
- 2 .;, C
. . . . . .
Session s & S s i o n . ~ : , s f ~ o p e n ~ ~ ~ ~ ~ ~ J ; ~ ~
,. .

.,:,

.g

,, ,

..

.
i
,
.
. . . . .
. . . .. . . .:
: ;:<.; ...;;; .if:'.. ; :.
.*:...
...; .
. ... .
+ .?* ..:,!>
... !..
:.:
.,
.:. :..
:
.,: .:.
. . ...
.'

.. ,

r.

.;

sd38ion.begin~ransaction();
.:..: ..,.
. .
. ;i.+<.

. .

- .,<...

...

....

I.
8

: ,

<, .: .

+..
,..:
- .:...,.,..
..<'3
. ,..

.~

. .,
._ :_
. .,, .:,.k :+: . I.. .-

.
.:

String&@
= "form corn.lara.Person p where piage-?";
* :,.t...;. '.;.I
:.:
. . ....
Querysyery = session.createQuery(hql);
:. --. ...$..
;.,_.:
: ..:_
..:>.
....
.?i
query:-~gtString(0,
"2
9");
:..
.
i..:$[?.:-.,
\

...~
.;.:t;:*

-,.

,,..
. :., ..:
<:. , ..
>....
:...*
<:. .?:.

'!

....
.........

.....
. .',#,.>
:
. ..,.' :. .
.........
.:.,!"
.,

.,

. . .
'I

.,. :
. .. ..
,... 7 .
.
. .. ... ..
.... . . ;,.. ..,. ..:

Iter.ator<Rerson>
it = quejr.iterate(>-;-i.. . . . .
. . . .
-.
whil&(jt.ha&&xt())..
.
.. .. . .
. i."'. . .
{
.....
P<&~=
.~
~ ~ ~ t e m . o u t . ~ r i n t l n. (. ~. ... g e. t p ~ + i ~ l d ( J . g . e t F i r ~ ( ) ) ;
,

~:

.>. .

. . ?

;:.$

,. .

!,

,. '!

.:.

.
*

...

session.flush();
Lara Technologies

080-41310124

..:

:
....

..)

',:

. . ..", .

session.close();
I*

// To read a record
PKField pk 1 = new PKField();
Pk-setld (1 01);
Pk.setFirstName("abc7');
Person p2= (Person)session.load(com.lara.Person.class,pk I);
System.out.println(p2.getLastName());
System.out.println(p2.getPersonAge());
System.out.println(p2. PKField O.getId());
System.out.println(p2. PKField ().getFirstNarne());
-

*/
/*

// To get all records


List<Person> list=session.createCriteria
(com.lara.Person.class, list)
For(Person p l : list)
System.out.println(p2.getLastName());
System.out.pnntln(p2.getPersonAge());
System.out.println(p2. PKField ().getla());
System.out.println(p2. PKField ().getFirstName());

/*

// To update one record


PKField pkl = new PKFieId();
Pk.setId ( I 01);
Pk.setFirstName("abc");
Person p2=(Person)session.load(com.lara.Perso~ 1);

P2.~etFirstName("LARA");
P2.setAge(6);
Lara Technologies

080-41310124

105

,'*
// To delete one record
PJSieId pk 1 = new PKFieldO;
Pk.setId (1 01);
Pk.setFirstName("abc");
Person p2=(Person)session.load(com.lara.Person.class, 1);
P2 .setFirstName(!'LARA");
P2.setAge(6);
P2.setLastNaine("Tecnologies");

Java Annotations

Lil

080-4 1310124

ra Techno:ogies

....

-7--

7-

--

I,:

y;.:
8- r . , r

The objective of changing older JDK versions to JDK5 largely


centered on enhancing ease-of-development. I n other
words, the new features shift the responsibility for writing
the boilerplate code from the programmer to the compiler. I f
the source code is boilerplate free, i'; becomes easier to
maintain. The resulting codes are also less likely to be bugprone. One of these new ease-of-development features in
JDK5 are annotations. Annotations are like meta-tags that
you can add to your code and apply them to package
declarations, type declarations, constructors, methods,
fields, parameters, and variables. As a result, you will have
helpful ways to indicate whether your methods are
dependent on other methods, whether they are incomplete,
whether your classes have references t~ other classes, and
SO on.

, ;;:.. . 'Annotation-based
. .. development is certainly one of the latest

.
. .. ..
.,. : ..

.
.
.

.. .
.. .
:

+\

.,

..

:.

l a v a d~e:y,elopment~?ends.
Annotation-based development
.,...
refieves:3:ava
.,; ,,:..,...
develo'pers from the pain of cumbersome
configuiation.
Quoting from Sun's official site, "It
. ..
; . ..(annotat%"-based development) lets us avoid writing
i : boilerplate
. .. cqde ,.under many circumstances by enabling tools
..t'&i.'
:,.-?,'
:generate it .from annotations in the source code. This
leads-to a decla'kative programming style where the
programmer
o../...
sayswhat should be done and tools emit the
code to~,~:do:;'~it.l1
simply speaking, annotation is a mechanism
for asso$ating. a met&-tag with program elements and
allowing the compiler or theVM to extract program. .
behaviors from these
.. . ... .
annotated elements arid generate
....
. .when n & & e ~ s i y -I ~
n.the first part of
interdependent codes
this three-article series, I'll describe some basics of
annotat-ion, their benefits, as well as some exampie usages.
;

..-

?:'

%. .

.;. ...
: .

.. .,

,?. .

:: : .

The Basics

. .. . .
..

-A

There are two things you need to consider with annotations.


One is the "annotation" itself; another is the "annotation
type." An annotation is the meta-tag that you will use in
Lara Technologies

080-41310124

!67

your code to give it some life. ~nnotationtype is used for


defining an annotation. You will use it when you want to
create your own custom annotation. The type is the actual
construct used, and the annotation is the specific usage of
that type.
An annotation type definition takes an "at" (@) sign,
followed by the interface keyword plus the annotation name.
On the other hand, an annotation takes the form of an "at"
sign (@), followed by the annotation type. This is simplest
form of annotation. Additionally, you can put data within
parenthesis after the afinotation name. An example of each
can be seen below:

Example toDefine an Annotation ( ~ n n o t a t i o


.. ....
n.$yp~)
. . .

public @interface MyAnnotation {


String dosomething ( ) ;

,.

...::,.:,;::......_.
:2d: <,: ..
,. ~.

..:.:;,,; ;..:
.

.:
...
. .. . .:.
. .. . .
... 5, .;:
.

:
.

Example to Annotate Yocr Code (Annotation)


. . . .
.

MyAnnotation. (do~ornething="t?hatto' do'!)


publie void.rnyxethod() (

I
Annotation Types
,. :
. ,,

There are three annotation types:

Marker: Marker type annotations have no elements,


except the annotation name itself.

Example:
.

public @interface MyAnnotation


1

Usage:

Lara Technologies

050-41310124

p u b l i c v o i d mymethodo

Single-Element: Single-element, or single-value type,


annotations provide a single piece of data only. This
can be represented with a data=value pair or, simply
with the value (a shortcut syntax) only, within
parenthesis.
Example:
......
......
<,~

. .
. . ..-.:.. .. . ...

. . . .

@ i n t e r f a c e MyAnnotation

. .
....

.,

-:;:,

S - t r. i n g d o s o m e t h i n g ( ) ;
.

1
Usage:

Full-vaiue or multi-value: Full-value type'


annotations have multiple data members. Therefore,
you must use a full data=value parameter syntax for
each member.
. . .
.;. . . .
...
..........
xa d,e:.
. . . . . .. .. . .
;. ;:. . :. . ::.,
. .. . .
.
...
- . . . . ."....
'

.. . .

.,

.,

,.

:
.A:

. . .:

. .

..

..

. . . . . . .
. :. ,.

. . . .

..

...

p u b l i c @ i n t e r f a c e ~ ~ ~ n ' n o t a t i{ o n
S t r i n g dosomething ( ) ;
i r ? t c o u n t ; S t r . i n g date ( ) ;
1

Usage:
@ M y A n n o t a t i o n (doSomething=llWhat t o do",
count=l ,
date=1109-09-200511)

. .
:.

.?,.

public void m y m e t h o d o

Rules of Thumb for ~ e f i n i n gAnnotation.Type


Here are some rules-of-thumb when defining an annotation
type:

i. Annotation declaration should start with an 'at' sign like


@, following with an interface keyword, following with
the annotation name.
2. Method declarations should not have any parameters.
3. Method declarations should not have any throws
clauses.
4. Return types of the method should be one of the
following :
primitives
String
Class
enurn
array of the above types
2..

1 <

Annotations

There are two types of annotations available with JDK5:


Simple annotations: These are the basic types
supplied with Tiger, which you can use t o annotate your
code only; you cannot use those t o create a custom
annotation type.
Meta annotations: These are the ar~notationtypes
designed for annotating annotation-type declarations.
Simply speaking, these are called t h e annotations-ofannotations.

Simple Annotations

Lara Technologies

080-4131 0124

110

C:6u!~ollo4a y j ay!l 6u!qjawos


3a6 IJ!MnoA lap03 a143 al!dwo3 pue ,,6u~~3soj,,
03 poy3au.j
~U!JISOJ a y j 40 a u e u aq3 a6uey3 noA J! 'aldwexa - ~j a
qw e u
p o q p h aqj q j ! s-lnxo
~
ay ejs!lu 6u!llads e J! suaddeq 3eqM
i
i,,

.:

> .
..

'

~:..ald,w
...
. . ex3

+,.

, a p ~ ~ x a n::::aueu
o. , .
uor~eqouueb u r q s a ~ ,,
+ . , ? ~ ) , -.~ a~ dun ~suInqaJ
,~ ~ ~ o ~
' ' ' } ~ ' ( ~ ) ~6ur1r)s
u~rr~
s ~~ o~~q n d
--apTrxaAoa
a p r x ~ a n g - q s a ~ssc;$3
.
. 3r~qnd
.>. .
}

-,

..

.. .
:uo!jejouue apylaho aqq saje~puollra'p1.
aldluex3 - ~ o i i a : . uaje~aua6
e
l l ! ~al!dwo3
~
aqq ! p o q ~ a us,ssep
~
--Iadns s ~ apy-Ia~o
!
qou saop- uojjejouue s!qj q 3 ! ~poqjacu
. . .

'

e 41 -ssep 3,adns ei:u! poylalu e ap!-IJano oyi:@aA!nba~


s!
poqjaw pa3EjOLiGE a q j qeiji.s a j ~ s i. p i cu] o j ~ e j o u u ea p j i. ~ a n out/
. . .,. . ..

.
.

::.

'

.r : ..
.. .
. .

. .

.
. . .. : .

.
.
.

.. .. ..

'

. .
:

- :i..,: ;..:.:

::uofieaouue a p ! j j a ~ o >; ~ ~ ~

..

'i

..

..

'sa~durexa
4 j ! 6udle'qjdap
~
w o w u! uo!jejouue aldlujs q3ea aqr~3sap
I[!M s u o ~ j ~ a s 6 u a~ q~l o= s~a~d o
A ~ ~ u o ~ j e ~po~ueu pe u e p
40 jas
e ayAM 03 stls~,~ia.q3o
o j pue s a d 4 uojjejouue luojsn3 a j j m
02 s~s-ii;we~6o~d':.a~1.ol
y a l seM 31 -hj!lpe.j ejepejaw e au yap
o j seM j! paJejs!p A ( p ! ~ pS L T - ~ S-104
C -lay ell:, a q l .aAnjeaj
uo!qeJouue ayl yoddns 03 A~!l!qea y j eAe[ a-IoI sMo(le
j! '~ayje-~
!suo!gejouue u!-y!nq Auelu aAey jou saop A l l e n ~ x
ley1 ajou 02 2ueyoduc! S,JI
.

(~a6!4'SPAOM ~a41ou!):s]:ac
... .. ...
. . .~ .
.

''

. . .
. ... .:

'

.. .

s6u!u~e~ssa~ddn~
pa~e~a-ldaa
ap!-I-lar,G

Compiling 1 source file to D:teinpNew Folder (2.)


TestJa~~aAppiicationib
uildclasses
D:tempNew Folder (2)TestJavaApplicationlsrctest
myannotationTest-Override.java:24: method does
not override
a method from its superclass
@Override
1 error
BUILD' FAILED (total time: 0 seconds)

The Deprecated annotation


This annotation indicates that when a deprecated program
element is used, the compiler should warn you about it.
Example 2 shows you the deprecated annotation.

Example 2
First, create a class with the deprecated method as follows:
public class Test-Deprecated {
@Deprecated
public void dosomething ( ) {
System.out.println("Testing annotation name:
' Deprecated"') ;

1
1
Next, try to invoke this method from another class:
public class TestAnnotations (
public static void rnainistring arg[]) throws
Exception {
neb? TestAnnotations ( ) ;

1
public TestAnnotations ( ) {
Test Dzprecated t2=new Test-Deprecatedo;
t2.dosomething ( ) ;

Lara Technologies

080-J131G124

112

The dosomething() method in this example is declared as a


deprecated method. Therefore, this method should not be
used when this class is instantiated by other classes. If you
compile ~est-~eprecated.java,no warning messages will be
generated by the compiler. But, if you try to compile
TestAnnotations.java where the deprecated method is used,
you will see something iike this:
Compiling 1 source .file to " ~ : t e m p ~ eFolder
w
( 2 ) TestJavaApplicationlbuildclasses

tempNe$;:kald&r

D:
-.
.: E
( 2 ) ~ ~ !btiC.
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ l ' i ~ ~ t i ~ ~ ~ ~ ~ ~
Tes'~~notations.
..
-java: 27 :
it

warning :p[deprecation].
dosomething ( ) ; i n
3;
........
test .myanhotation.Test'.~eprecated
has 'been
deprecated.',!.',:-;
.
;.:,;: *
..
..
.
......
:-t.2
doSometh2ng3;(i..).>;
....
.
... ..-...
..
,..
:,,:..
....- *.;: ..*<.
.:;,
. ,.*:.
..,

...

.z

-.

,
,:.,:
,, %.%$:

Q;,-

..
.

, ' I
.... ...,..
?.

....

.. :..;

,,

,%

. : ....,.:
. .. I. .,
%
. . .. . .. . .. . .

.:

..

. ........ .. .. ... .. .. . . . . . . . . .
... ' ; : .
:
. . .. .. .. .. .. . .. .. .. .. . . . .

%~+;~,&~~$~;<
.,+<.
-:...
?. *..&"*-:
<.<
,Li3:*&*. , ' .:
...vp
;:,>
";+.&
', . ..

..

.
.
,.
. . .

. . . .

..

..>
.?:?ii4j.:;.';;

mn..fn.gs
a,,n,ota,tio

<.,::-;.::$;'?
;,
:~<*,

2.s:":q,reswa.

he

.. .

. ;*-..

,>7

>..

.> .;..
i

v:.

. .~
<*:?: ~;:
:.-.
;
.:.:,. .:
<:,.
..; <.i-lj
.
: : . ....
. .":-. : ~:y,:~ ...
~ ~ : ~ , < * :~ . j:+x
~
,i
.:..
. . . . . . . .'i.

=..,...

.
......

:,

;"-';.,".:'

.-.

1 :!,*.;:$..
:.. :.,::.. .
. .. . .. .

,..: ;V :..'. .::.. .


......::..:.
......::.:i:.: . ;: . .

, i;:;$<jlwaming

. .

.. . ..

:.,

: .' -.::

-?~C.L:.

......
::,::.? .;. .<

>
.

. .

This ann0U:tib.n
indicates that compiler wamjmgs
should be
.>, ,:.
...I',.....
:<,:
.......
. .': -Shielded in'tKe$nnotated element and all of:its
sub. ,.
....
?e@ments.
s,.,..:
~h.k.'s.et
... ..:y;Lp..of warnings suppressed in an;element is
the!:s$perset
.:: ......
=:.
of;;tb:e
.%"..
warnings in all of its containing sub.....
elernetits..
::.~g~qP~...
As an-example,
. . . .
if you annotate a class t o
suppress$ane
Is'.,yz..:.. :, wariing and one of its methods: t o suppress
.
'i
.c.. .~
r
n
'
i
n
g
,
b
.
o
........
t h ~ w a r n i n gwill
s be suppressed:af:the
another
method level_io"ly.
.......
SeeiExample
.....
3 for theidfipresskarnings
..' .
;..
. . . . ... .
. ..... .. . .. .. ..
.'
...
.I.... :..
.. :!,
.
annotation.
.
:r; . .
.: :. .........

. .

,.

. . . . ..
. ., . ,. .. . ...+
-i
.
.

;t....--,Ln.

,.

x29.G

.,

.:-,%:#.:

...-.

.!

I
;

.-,

..

.'.'?.'.

.:

... L ..

s t y .:. ,:.:.,.

:;I .

..:. --..

.: ,

...

.r.

........

<:.

,;.
,

'

.-.. >.:.,<rV:-..I"..
. a.
. . ....,:<,I...:
.,r.:..
. .-

.!....

,,.....!.
-;
.>

..

;::;.,; ..
..,,... :..:; . . ,".
7 .,,..
:..!,:.$;::.?L<

*>: .

-1

:, .;

,..

..
,.... 1.
. ...l;..
:. ;:. *.. ::..><...
.
..
. . . .

>.,

.;?,

....

.f,::.i,'.

'?

. .. . .

...
Example 3
,
.,
public class ~estKnnotations {
public static void:.hain
.:.. . . ..:.
.
(String arg [ I ) throws
..
Exception {
. ............ .... .. .. ..
new Test~nnotatidn.&():.;
dosome~est~o
( )w;
........
. . .
:!,=b.

?.:

.:

...<.

.t;. : :

.;

....-

1
J

.. . . . .

@Suppresswarnings ( {"deprecation1'))
public void doSomeTestNow() {

....
..

;'.).
:. :
....

Lara Technologies

'

'

T e s t -Deprecated t . 2 . = new T e s t -Deprecated i ) ;

I n this example, you are suppressing the deprecation


warning for the method listing shown irr Example 2. Because
the method is suppressed, you-are unlikely to view the
"deprecation" warning any more. ':
--I

Note: I t is a good idea to use this aiihotation at the most


deeply nested element where i t is effective. Therefore, if YOU
want to suppress a warning in a particular method, YOU
should annotate that method rather than its :class.
.

--

<.
.. r.. ;.. .

Meta-Annotations (Annotation Typesj

....

..... ..a!<t;. .- 2 g;9. 94


. :::,.("C
<.

.-

...

...

-.

... P.; ,?$.

%Meta-annotations
...
are
actually known as
..<'.
'.::;which
1
:..
.;.4;:+::..<,.
.;.., - *."
..>.
a'n:Qotationsof a n ~ ~ f & i o n s , ~ r j t a jfour
n
...
h/pes. These are::!
-. ...? :. . .: , . I I
.,.--.... ... ..
'..!,;:?.>
.-: .'.
. !.
.a;..-.
........
..: .;.. .
. ; ; , > , , .. .. . :.. . . .
.
. . .. .,.... - . .. . .
Target:
. . . ..
.
.
.
.
.
.. -.:,.
.:: - 4 ' ., . . . .
.> . .. . ...?:. ?:I. .
:;.::?..:
Retention.
... .'+.*: ;.;<
".....:
-.
Documed:ted
:,(,.:
* :!::':, ,
.. .*.
...
.*..
.. +:
. , !'?.<,.,r . 1nherited;ji:!:..
,. ~ 5 s
.~

: .<

.?,

:,

. . .

.::3:,-

. W

i.

;
:

.;

.>.:

.-.

:.

I,.

'
I

>&

.. . . . .
.:
. ,

:.

2.

>:

..,

.',

:<
.

.+ . :

I
:

.
1
'

. .

-.

.:;.~,

r.

;:;,.

5,

-.I.%)
>
......
. . . .>,.

. . ,
.

.?.".

<:

The Target annotation

The target. annotation indicates the. targeted elements of a


class in which the annotation type will be*applicable. It
contains the following enumerated types as its value:
@ T a r g e t( ~ l e m e n t ~ y.pTYPE)
e
-can

be applied t o any

element of a class
@ T a r g e t( ~ l e m e n t ~ y pFIELD)
e.
-can

be applied to a

field or property

. .
@ T a r g e t( ~ l e m e n t ~ y.METHOD)
pe

-can

be applied to a

method level annotation


@ T a r g e t( E l e m e n t ~ ~ pPARAMETER)
e.
-can

the parameters of a method


Lara Technologies

080-41310124

be appiiec to

114

-.

I"

...
. . . .

.. .
.: ..

.....
-.

.-,

@ T a r g e t( E l e m e n t T y p e .CONSTRUCTOR)

-Carl be applied

to constructors
@ T a r g e t( E l e m e n t T y p e .LOCAL -VARIABLE)

--Can be

applied to local variables


@ T a r g e t( E 1 e m e n t T y p . e ,ANNOTATION T Y P ~-indicates
)

that the declared--typeitselfis an annotation type


Example 4 demonstrates the target annotation:
Example. . .4
..
:.

.>>.

:.
*....,

..

First, de&e.. an annotafion


'named Test-Target with @Target
......
.. . .
metadat$,:las follows: ::..
$;5j..

....
....

7.:

@ T a r g e t( E l e m e n t T y p e . M E T H O D )

-.

r ..

.-

,!ii.
.:

p u b l i c @ i n t e r f a c e Test T a r g e t {
p u b l i C S t r .i n. . g: .. . d o ~ e s f ~ a r q e t o ;
. : .
5. . . .

. ;.

. . . .-.

=-:?.%.:. :

.A

::!;.:;
:: , .;.

... ...-,:;
a
.
,
.
"

:.:
.?< "
:
c
:
. $i.
. :, ...:....;
,,,

-3.

<.

;.

s-;
.::-s2@&
,%
. *,

.
..

. :.

... :.,i.:.-.;,.* .; .: '...


;
;.:,.:,:
;.: .=," :, :.;.. . ;.:;::;.:;.;?::; ': . .,......
..;..
. .
. .
..
I.....
'

'

.*.

I . . . ;

.<

/_

,.....

'.Y..<.
. . .... .. .
. . .....
.......$..
P,.... .+
.:. ..
'3.;. l.
;.?.
..
_..
I ' ..
.:.....; .>-.
:. .?.
: ._. . ,...
.. . .. :~ . k

?.

:.

:.:

.
.
-:: . >

.
. .

. . ..

-:i

.. . :.:

. .

g2.:, .'.

.
.,.

....: . .+., . . : - ~ . .

V"

'?:''.

'.?.

:!.,.
. . .*... .

. ;;'\;,

<
:-,

.
.

-?:g,,&'
;. ,.:, :.:; ,;.
Next, .,&e_eate
a class t ~ s e
. . . .w
. .J.l;i,u&"the
.i
,Test-Target
. . ... . . . . ., .... :.,
.
Y$y&g;:::
..::
. .. .:. .. .. .. .
annotatrQn.:
....

.:, * :
i

.>.

:.$.....>f...ta*:

.
...

......
..:.
. . . . . . . ..~ .. . .
.
.
.
.
. .. '..
.

'.;:<;,5<>,.+,>;:.

.: :-i.1;:
. ,;,,.;.

: ,

.:.?-i.k?'<'.
.L*
,;. !:. .....L.. .

.:....

.I.

.
.

.
>

\I.

....
.:
,

<-.; ipiublic
. ....
c l a s s T e s t A n n o t a t i o n s . .{
.:. .... .::..'.!.
: . : ; i-........
. 5 ~ - p u b l i csta'csc void m a i n ( S t r i n g a r g [ I ) {:
.
.
..
'";,;i,'::$jnew
T
e
s
k
j4nnotations () . d o T e s t T a r g e t () ;
........
. ..a:%+.
...
&...

,:.,

$.

>

-..

j.

p.&<%$#+&
&%.
.

"i....

. . .

@ ~ & $ $ ~ ...j ~ ~ ~ ~ ~ t ; , ( d ~ World


~ ~ ~ t ~ ~ ~ ~ ~ t =
!I1)

*$$$-. .

.,. . . ; . . .

publsb.i:.yoid
.
:.
d&estTarg,et () {
*.:.: j-.
sy;tem. o u t :!. p3;;.
~&
n ; e z , ( ~ T e s t i n Taxget,
g
.: :.$y.:. " .
;:.....
..
a n n o t a t i o n " ) ; 1:
..,..: :'-,?, ,.: :,:

:-

';,

'<>,

."

.!

...;.:,

"

. . . . .

': .?.

. .

The @ ~ a r g e t ( E l e m , e n t ~ y p e ~ . . ~ E ~indicates
H O D ) that this
annotation type can be u$edr.to
,::..7.,tF..;..
annotate only at the method
.
. ..
no warning
levels. If you compile the p.i&edi~g.code,
messages will be shown. Now',:,i:f$$~ou
declare a String
variable and apply your newlyicreated annotation, what will
happen? Let me demonstrate this as follows:
:

Lara Technologies

public class TestAnnotations i


@Test Target(doTestTarget="Hello World !'I)
private String str;
public static void main(String arg[J) {
new TestAnnotations().doTestTarget();
1
public void doTestTarget0 {
System.out .printf("Testing Target
annotation");

.. .

. ,.. ..

The
you..can see from above:;is:iaat the
annotati~&n'-declarationisshifted from me&od-.level t o field:. '>!
level, w h & h ~ i . ~ n correct.
ot
Because you have defined your
e applicable
t
only atmethodannotation ' ' . d ~ ~ s t - ~ ator ~be
l.evel, if you t$to
compile this class, you are likely..:~: get
.
?.

.: ...

~est&n.o&.ations. java:16:
annotationi.~kype
not applicable to this : k i n d of
; ..
. .
:.de:,c:larat
...
ion;i~a,t..
. ..
line
... ... ... .
'. .:.
1 6:%;i'j.c0
lumn
0
%
':
..
1j.f..
.*..,
. .\
{;do~est~ar~et="~ello
z.--:
World ! " 1 ' j L .
@Te's;t.'$I!!arget
-: .,:
.. .
-

.., . ,

:, ;.,:
?

. ::

,-.

,.

,.

.*>

..

..i-P&la.
'.,,. ...

At:.

... >

..,.U.
? :..

.:L

$.

;9-.:

Error Gn: ja:'*. i, ;


c -compilation
W .
.. :.

*:<. ;' :..

..+

. .

. .. .. .
,.,.:> .
.:.>. .
I

, ,

The retention annotation indicates where and how long


annotations with this type are to be retained. There are
.
three values:
i

RetentionPolicy.~~~~~~~no
with
t a tthis
ion
type
s
will b e by retained only at the source level and will be
ignored by the compiler

Eara Technologies

080-41310124

116

RetentionPoIicy.CLASS-Artnotations with this type


will be by retained by the compiler a t compile time, but
will be ignored by the VM
RetentionPolicy.RUNT1ME-Artnotatior~s with this
type will be retained
.
by the VM so they can be read
only a t run-time,,. . . .. . . ,,
,

,I

Example 5 shows yo" the RetentionPolicy.RUNTIME value i n


action :

Exa mple;;.5
+:5z
.

...

.,

cRetent$on ( ~ e t e n t ; i . o n ~ o l ' iRUNTIME)


c~.
p u b l i c @ n t e r f a c e > ~ e , sRte t e n t i o n { "

striGg

d o ~ e s t ~ e t e n. . . h i (o) n;

..

. I

...

...

$.-.*,::>::
3 dn,
t*.*h... i s examp1e;;:the.:4;.>-. @~etention(RetentionPolicy.RUNj-IME)
pz
.. :! . ,:.?>..
::. .;"
.: : ;:;;;: .;.:a
G!notation
Test-Retention a
is
. ..-. '.: . "
..:.Is;$@. indicates-~~hat-you,r
.. . .
.. .;:., -.:.
C.!)
. :...I ;
. . . . . ..::c. . ...: :.
': .,....... .
. .. . . .
.
,,.:..:.

.<,>

n,not&&h.

.'<

>a:.;-.

. . ,<:
:
........

-&:.: :.!. ..,?. ....:...


".,..- .
.....J:
. . .. . . .
I

<

..'I."

to'be;te,Qajned
-:~&$@p@~. by t h e........
VM;.:so.:jt,hatit
...........
..-...
,;y,'.OY;.
c a n be read reflectivel.y:.at
.
. . ..>. ..'...... . . . .
t-un-t~y@g;.
-. ...,-..
. :.::.. . . . .
. . .
A<,....--i
...,?:..?..
I. :
,, :
: .
.....
. . . .

>,A>.

rL ?.

:. .

.- .

" 7... .:.

. . .

.,i.

....

. .

should be documented by the javad0.c tool. By


are not included in javadoc. Butif
it then will be processed by javadoctype information will
,..a,l$lj
be
. . . . . . . . ..,+.
Example ,G{;.;":;'
"
:'

. .....
.::,,.

Example 6

,..., . ....
. . ..
;. .. .. . . .... .. . .
. .::.
... ..... ... , ..

',.

."

..

. ... .... ....... .. .. . ..


.... ,...: .r. .

@Documented
.
........
p u b l i c @ i n t e r f a c e Te~.t..~jDocumented
{
.....
S t r i n g doTestDocurnen~t;~~~):~;.
..,., ..
;

....

:"

c..

>. .
. \ i

.'

....b...?.. .:.., . . . . . . . . .
,.;:.. ..:',
?','. :: .:
....
:,. x......
. . .','>.. . . .

..

. ............
.,. .:
. . .

Next, update your ~estAnnotationsclass as follows:

Lara Technologies

...

.. .

.. . ..
: ' I

public class TestAnnotations {


public static void main,(String a r g [ ] ) .(
new ~est~nnotations.
( ' ) .do~orne~est~etention
() ;
new ~est~nnotations
(:).;:do~omeTes
t~ocumented( ) ;

.
..>..;

. ..

,..

@Test-Retention (do~kst~etention="~ello
retentior! test"1
public void doSomeTestRetention ( ) (
System.~ut.~rintf("~estin~
annotation
'Retention1'') ;
@ ~ e.ts: ~ o c h e n t e(dd o ~ e s t ~ o c u m.. ..&
. . h t = : ~ ~ ~ e l l o
.. .. . . .
document1'.) .
. .. . . . .
p b l i&:.void
doSomeTestDocumented $:.;.it6..,
.+ .:
..
'' ;
;..
System.out.print-f("Testir~gannoetlon
. . !i. .;: :i.::r
lDocument&Vtl?;
.
:.

. .. . .

'I

;,,

*::

?5

P.,.

. , ...
. ./<
.ib
1,;
,.

I . ,

..

1
1.

-:

.
.,..,

,.

;>:

. . . ...... . .: . . .. . .
.. ..: .:
. ...... .,.
:
, :<:, ;. ..;
. . . .-.. . . .>.
.

.
;

..:_.
:. ;s< .<!;.
...... .\
... . -.. +.
....~
.. ..?... .. ...".. . .

. . . ..
...

.
.:

.....

+.:;

. . .

...

. '.

;.:

.
.,<< ., , $.?
:;

I::%.

. ;,. L*.;?
,,:

,;::'.i.f: ,,you
.;
run the j & i G o c '~8fima"dand view the
,

?>

i'

..
;..!:::

-:

i
i

:.

.:- :.

.!:.,
No
..$.<
generated
.
~ ~ ~ t ~ ~ ~
... _:. . ~
. . . t 90"
~ will
t . i see
~ something;
~ ~ . ' . : ; h ~ ~ .... ~
.
1 i ke Fig
..
.
.
:.

,,

.. . % .

. .

Ls?ra Technologies

:.

....

. . .

080-Ji320124

: 2.

'

.:

...

-.

'
7.
i
Constructor Detail
~~

--..-

-.

- -.---.-- -.

---...-,

&I!

-/

>

"

I public TestAnnotationsi)

II

..

1 Method Detail
!

main

public s L a c i r

,..-CILJ

r a i n (lava. l m l g . S t ~ l M] arg)

doSomeTestRe tention

.
.

I!ii
1:

1'

..
.:..*.... ' . ,:
.:
.,.,I
.. .:%.:..
.
-.
.
. ;..
.
5 (,. .
%
. : ,
, . .. .
.... ,... .. .

,.

I I.
:

...
...

i ;.

public void tloSomeTestRetention( )

I .

...,.

'

.
.

doSorneTestDocurnented
:

...

I;

f l c ~ tD o c ~ ~ c d l - 3 0 T c ~ ~ 9 i ~ : v ~ ~I co nddcwant-)
c~~Hc1

public v o i d cloSorrTcstDocumented ( )

-5.
'..:.hi
..y
~

'::

j
i

:*.-. l

:i

..

..
2 ,.:3:

.< ,.:-. :rz,

:.>

. . -.,
.. :!:

-.

?.

Fig,die
L..i':-

< ",
.......(:,;:... .:.:y,<:f+,
:,
..,. .Lt
,;,.:. .
.. .?..
a;
F..:?

..,

.\.

,??

AS you qa.n see from t h e screenshot, 'there is no annotationmethod.


.
type information for .the:do~orne~est~etention()
.
But, this description is provided for the
.

doSomeTestDocumented() fnethod. This is because of the


@Documented ta g attached with your Test-Documented
annotation. Your earlier annotation Test-Retention did not
include this tag.
The Inherited
annotation
-

This is a bit of a complex annotation type. It indicates that


the annotated class with this type is automatically inherited.
More specifically, if you define an annotation with the
Lara Technologics

@Inherited tag, then annotate a class with your annotation,


and finally extend the class in a subclass, all properties of
the parent class will be Inherited into Its subclass. With
Example 7, you will g e t an idea about the benefits of using
the @Inherited tag.

Example 7
First, define your annotation:

.'
I

@Inherited
public @interface my~arent0bj6ct {
boolean isInhe.rited( ) default.true;
String doSometlling ( ) default "DO >what?";

1
f

Next, annotate a class with your annotation:


I

@myparentobject
public Class myChild0bject

I)
,

-.
, >
r.

r 'E'

-.
{

As you can see, you do not have t o defhebt$e interface


methods inside the implementing class. Theie are
automatically inherited because of using the @Inherited tag.
What would happen if you define the irnplementing~classin
old-fashioned Java-style? Take a look a t this-defining the
implementation class i n an old-style-java way:
. -.
,- .
2'

,::... ,, 5%
,,:
.,$

+;'

:i.
.,.:-*$
. ;; ..""il
: .:.. :..,. .~<...--.

.L

public class myChildObject,,implement&:.,.;-:,


Ci''
.:
<..
myparentobject {
public boolean isInherited() {
.
.
. . .. .
return false;
;

. <.

4,.

-,

I .

public String dosomething() {


return 'l";
1
public boolean equals (Object obj )
return false;

1
Lara Technologies

. .

:.

public int hashcode() {


r e t u r r ! 0;
i

p u b i i c String ;tostring() {
r e t u r n "";j
j

p u b l i c Class k! In o t a t i o n. T y p e ( )
r e t u r n null;

"i

*..I

....
.

2
.

:.!. .

Do you see the diff rence? You car1 seerthat you will have to
implement all the methods that the parent 'interface owns.
do~omething(.)fnethodsfrom
Besides the. isInheri
myparentobject,
to irnplernenfthe ..equals(),
tostring(), and hascode() methods of java.lang.0bject
. . .
and
...
also
. .,.
the annotation~ype()rnethod of
dava.i.ang .a n n o t a G o n ; ~ n n o t a mclass. It does not matter
want ~o.~m.$~m&nti&hese
.... -;.; ,-..;.
methods o r not; you
wh&-he.r:you
1.:27. 'p;. .....
will h a v.....
........
e- t o include thesein
nour:.iinherited
object.
.
.
. .,
:i
..\

.-

:;:.
f

.
.. . .

>

;>;:
..........
.:::e

:..

!:
n.:z
,.".

. .... .
.':

. .>;

..: ...
..'...! .: .:,
........ ....:.,:
.'. ..
.......
" < .. . .
.::..
. ...
......
.<
:.. . . .:1 C
. ..,
. . :. . ...

. . . . . . . . . . . . . .
:

: ! ?.

;. .$; .. .:j .:;


:>, .;.;,. ..
..: ; c ; <.:;. . . -.
,.
. ... . .
. ... ..,. ... . -.,. .. ... . .. . . . . .
. . ,
.
:?

. . . . . . . ... ,.
...

".

..:

Lara Technologics

080-41310124

:.

'.

....

>.,.:.

.. . ..<!.?.
..:.2i:;.: ...... ,
-,.....
........
-.......
..
.

,..,:..?.. ?$. <,.

<.:.'>!. .

:3>.
+
.;;
" :

..:

.,.

.&':;.'

...

Using Annotations in Bibernate:


Annotation is for providing meta information. It is introduced in jdk5.0.
Annotations provide data about a program that is not part of the program
itself-they have no direct effect on the operation of the annotate.
There are 2 things u need to consider with annotations they are:
.

.
...
.: -:

1. annotation: the mega data that u will use


in ur code to give it some
. .:,
life. It is sp~&ficusage of that type." , i ...(1..
2. ann~tation~tlpe:
. , . .
is used for defining d.&u$otation.
It is actual
.
.
.< ,.'

.-

c..,

;:

....
: ..' .

.\>

. .

constnjct
us,',-"
i.5-

3:

:c:<

.,;, .

.. ;:
, .?.
.;

7*

"

,. '.
..:. !:.
..

:.;

: :; :
.
-,...: ..
?

;', ;

:.

..

... .sir<:.$.*
. *:,;- ;R::%.

-.

. :1

:.-.;...*.'y;..>:
*.\.
"t

There are three


.
types of Annotations they are:

.ci:F@:k.
;?: +.,

. .

,,

.
t

Ir:. :

. . . ..;-. **
,.:

....

1. 5<~i;hei;i
SGs iype 'nave no eiements,except the annothtt6@name
...
itself.

....

>....A..

t,:cpF
. . .
-......
. . . I .:
,c
'. ' *. . ,.. ,

..;

'

2.

::..,,~.,:....i >.n g l e - ~ l e m ~ : . p r o v. i dasingle


es
piece of data only. This'<&., be
:'
?:xep,esented
?+>: . . . . .
with a data=value
..~,
pak~qr,..sjrpply
_ .
with the value onl*.:. ,,..33 :2:. .;
the peranthasis!
. . . ; ' .
. ..:< .:::
- . ..., >. : . . . .. . ; .. .. . . .
........

. . . . . . . . .. . . . . . , . . .

.;;.

::i:

.. . ..

. <

i..

. .

. . .. .. . . .

...

:. ,?

:.

. . .

t ' . . :

. .. ..
.

*i
$.

3. Full-value o r Multi-value: it is having multiple$a@ members. we

must use afull


data-alue
.
.

us4

.. . . ..

. . .. . .

.Q

..

,,,.,

.'..,...:, ....
,

. . .

;<,

. ..'.. .

..?..1.:

'

I.,-

. . .. ..
. .<'. *z,<,
......

.>

...:

-1.

.::.... i
;G:
,
,,:
;.

: ..%

:;..c2..,
.- ; ..
.....

'C,

.- I..
. . . . . .
. .
.
.
.

parameter systax for eachimember.


.: 2, .

. .. . ...

.,s .of.~nnotatibhs.&re:
L at;,::...:~i:L
..... ..,>.
. . .'... .
,.

.......

,., ...
,. ..
. :

.,., . . .
._i

.
:
,
.
.
.
a
.

'-

I . In"formation'fbr':the compiler: Annotations can be used

compiler toidelete errors or s u ~ r e swarnings.


s
i.

6%ihhe
! .;

,.

k:

..,.... .. .=...

. ,

.... . ,;.,
... . .

. . . . . .

..- . . :.
.

. . ...:..
,;

<

2. Compiler-timeand deployment-time processing: softwake tools

can process annotation infonnaticn to generate code ,);h.lL files and


SO 011.

..
3. Run-time prueessing: sone Annotations are available to be examined

at runtime.
Annotations can be applied to a program's declarations of a classes,fields,
methods and other elements.

Eara Technologies

.;:

. . . .. .

. .. ;'
.
,.

The Annotation appears first, often on its own line, and may include
elements with named or unnamed values.

Instead of writing nbm file we can keep that information, we can write
through anotations.it M ;I1 act as a member as like class,interface, enum
etc.anotations mainly to give.

Annotation is also getting a .class file aslike class,interface.


.

instead of providing documentation


...
and comments.
we can useAnnotations
...
. . .
. ...

.:.

. .. .

The rules f&developing an annotation:


1. m o b t i o n contains only method definitions.
2. methods should not take any parameter and shouldnot throw any
exceptional class.
..............
-.: ..,.
..:7:;<:5$
.,:.-,: ..
3. return type of method declaration should be primitive ore@ibg
.-.
..: . or
<fli
1.P,2 .g:
.
,
,
;
.. ,,:;~k,.z~class
or
ennum
orl%:ayrof
the
above
types
but
should
not
be.:~old.
.....
*. .,.. :., -. . .v,4 ;;.. ::.
. . .
.
.:
<
3
::..:
.?,annotation can b e h s ~ d f o ~~asi&/~acka~es/methods.
i
.
:.!
$
:<:::
s."~
tl&@gh target we can-able t o fix t o 'classe~/~acka~es/rnethods.: .
a,*<;$+!
. :.::<.s.:.
. .? x
:,:.;<
6 . if ' G e t is type, we can fix a.matations'to
... icl~s/interface/methodsi~~~.
,.:.
: ...2.;::
..., ..... . .
.. .k:E
.:
,,. ..' .. ,.:
.. I. .
..: _.:.
\..>.::. ;:;$:..
7. if tar;& is field, we can fixannatations to cl6s~~s/.in~erface/methods
. . . . . . .>
,.;-. . 3' ..:
;:.,:::
. . . .... .
.

'.

...

.$.:... .

:%:;

':i

'

<'

y;,I .:.....

-.::

5;

..:

.#: ;

:.,:$.:$.&;:<.?.

:>

..:.

&,:
,
. . .

.-

:t?

7: . .$ : .:::**d.
.-;
;I...7 z

:?y

czs

,a

<.

A
,;+
*.,.

i,

?!:

. . .

..

!.

..

>

.&
$,:

.::

%.

'

. .y:, ..?.
P
..
; <.;

% ,.*;.:%.-%
' .
*:+<:.

<
.:<
,

'?&;&$arnle
:
*:..

. . .

...

,. .. . . . .
. . I
.

-.. -. - . .

.:pM;s;-;.
.'. .

.
~~b]f;$l&j,Test
(..;;:?.+
.
.:.::;

..:..
.

.%
.. . .
....
% .

.-.
,

. . .

-5.;

.i,...r:.
:......

.L?~."

.. p t . : :

$+>.

, .

.......
@@pe~ride
.........
Public String tostki&.

..

.
.

..

.. :;.!.
. . .

Return string;

., ?.
.. . .. ...

...
A ,

. .
.. . ... . ... .. .

.
. . , . >, ..: ;
:
.
. . . . : ,: . .

Ti

.:

..

.:.

..

.. . . .
.
. ..
.. ::......:.=:
.i;.<.>.. : : . ;
.. ., . . .:.
.
,. ., .

..

@Override: indicates that annotation which provides meta information to


that tostring(). I t is overriden method i t i s not your own method @Target: Annotations can be used in any of the place by defining target.
Need to fix the target to where to use that
Example:@target(Elen~entType.type/method/parameter ...etc.)
Lara Technologies

080-41310124

,
:7

. .

.. . ... . .... ..
, .

..,
" q..
;. ..'. as:,:,

'

..

,- '.

:
.:-

@Depricated: we can supress the de~ricatedmethods.


@SuppressWarnigs: To telI explicitly to the compiler
Example: @supressWarnings({"depricated"))
@Retention: Whether this annotation want to display for particular class or
for particular JVM thenit is limited to that not for the otjers.
Exaple: @etention(RetentionPolicy .class/runtime/source/. .. etc.)
@Documented: when ever you are using this motation that .java file java
documentation method is available.(it also should!be documented.)
:, .... hbm file in
To use annotation for pr0viding:;mappinginformation without
the hibernat<;To avoid mapping resource inside hibernate-@qping
......
tag.
For that update the buildpath with 4 types of JAR files they are;;:,
. . .
.
. . .

. .. ..

<?..*:s,?
.,,
.;:$::, .s.t<::
.
+ .*b.~J>i s s>: r..3
:j ...: :
.::*.;

,., ,:;

.,

:.

;.::sl.:?i-.hibemate-3. 2'g:j
ar afid
dent jar files.
....
,.. \......depen
;:i3&c$$tggg2#.+;i:;:;.>t>.
x
. . . . ' . .. '*
.-;.E"'.Q~cle
4' rype &jO&&JAR &le ;:
. . . . . .>?
.
.*
..
,*+.

-..L

.I:::.
t:- .
L,;

....

c:.,:
. ,:.....
.

.;

>.

. . .
........

<.

. .

'.

... . .i.
. . ... .. . .. ,.
"i

'

5..!,

,:

.?

,.

t..

clas;' A; ' . .
.
. . .
.
{
Bdiprecated
String test()
..
.. . . . . .
{
Sy~tern,out,~rin't~lri(~~i~ricated
method:');
..
.

. .

.$.

,.

.:. .. . . . .

..

. , >..

Class Manager
{
Public static void main(String args[]) .:,
{
A a 1=new A();
A 1.test();
:

Lara Technologies

080-41310121

,'
i.<i!
>.,"::::
.;.!+
.......
,Icsr..-..
.w,c.
........:*.i?.Y.
..:.
.....:. .:
<:.A

3.~&~fiamework-2.0.4&ith dependeniies(re1avent JAR files).


4. ejb3.0-~ersistance.jar(must and should)

. . .

..: ...
.,:.. .$

-:.

::.

3:.,i::.

:
,%

..
....
3 .......
....
. <. .!!.,. .t:. y..
. .,. ,. . .
f '25 :,;, $
:

'

y . ~<....>.
5 ; .::. :..,.%-. >
.:.

.... ,.

.:.

I
class Test
{
@TestAnnotation(count=l 00, date=02-02-2009)

I
Example: hibernate prograrne with usage of annotations.
.

import j avax.persistance~~.co1umn;
import javax:persistance.entity;
import javax.persi&&e.ld;
::. ...
import~javax.p~rst$~~e.jable;
. . . ).:
. . . _ _. . . .
.
'

.,

.:

..- .:,

public vai'~'~setPersoriId(String
.... ,:, .
persodd) {
..
this:dersonId
..
= persodd;
,'.

5 ; .?
..A<

j
.
.
.
:
.
.
.

>

public String getPersonName0 {


return personName;

public void setPersonNsme(String personName) {


th is.personName = personNarne;

Lars Technologies

pub!ic class
{
Public static void ma@(S;@ng.pgs[])
.
..
.

'

. ,

. : . :. .. ._.. .,.

...

, ,'

Person p 1=new person();


P 1 .setPersonId(l 0 lo);
P 1.setPersonName("UDAY ");
:

'i.

&~:::hotation~o~fi~wation
,
ac=new An$tatioqConfi.gurati~nO;
.......
. . _ :. _
~":ac.configure@,,
.....
...
'.;-session~actor~
sfac.build~ession~actory~;,~:
.
Session ssssion=sf.openSession();
. . . .

T
.:,.!

.,

<.

::.r:.. :.

::

:.

...

. .,.a< .
..'!-.
..

,;

. . .....
. .:..:...: .
>$.

,,

.... ,$<,
.....

. .-

. ....
.=:.. .! 1....,.:..
.: .; -. ..

..>:,.:.:
.......

.
..
'..

. . . . . .
:

:. . . :, . ,F . :.:., . .. . -..
.. .. . . . . . . . .

. .>

.
.:.$.;

.:-:, .
x.,.....
:.. . .
-;.
.
.:.,:..,
;.,
:,..?:.:,.;:i.'~::L

..::.3

.!.,:.,...

'

'a

~.

'

.. ...

'

.-. ..;:

.,

...

:.
,:.......
. . 9 .

,}

.
'

<,.

.. . >.

. . .

.,.,: >'<.&.....
.

:'I.,

.A

<

... .-

..........
.. ....,..-.
....
,-, ..
.,:A:.

,.:. . ;,*.
!>

. . ..

. '.aa:.'. , ..
. . .. ..
:

%
.?.;:..

..

$.

......
... .. .;. ........
. ,'*.>.. . .
:...
-. .'<,$;.<.

...

. : .. .>
.. . .:.
I
. ....
. . . . .
I
..,
. .'. .. '
+/
'

..

. . <..
'

'

. . . , :.

'

. . . I . .

. . ..
A

.-..
.

:.J

Lara Technoiogics

I_'
- :
:ih .......
:.. ? .
.:r

.. . .. ..- >:.; ,
.r; ,.;-.;....... . . . ",..z.
:;..
..
..........
.>?, !. . .7 :
...:.. <?.;":.
......
;, ,)?.., . . . . . . . . . .. .......
...
.
.
.
.
.
.
.
. ;;..
. . . . . ,:. .........
... ;.,:. . : :. . . . . . .
.. :
'

:..
...L.', n..:
.
.,,.:
.,
.*

. . . . . . .>.. . ::.. . . :.
. . .. .. . ; ..
. ,
: . v
.:

...

;<:. .'.
...
:...".
. .' .

j.;

,.

080-41310124

.....

,:: .. . .

.. .:....
.:
.'t.:
..i.
,.:

......
. . . .:..
..........

:. .
.. ... ..
......

. .

.-.-.;.,+
.. .... <
..-.; ..-....
:.::;+.-

..
..I. . . . . .
...........
.
,

Ssssion;fush();
Sessiop.close();

..
,y
..
. ..: : ..
..I
. .:-,,
. .. ..+..:;;?>
....: .. .&
,. .?.; . :..
.

. .. .,..

.
.

i? *

. .. .
. ._ .:
.. .. . ..

<

; , ;.. ..: ,. . . . .

..

.
i

i.'.:

-:~:i.r!
..I' .Session.getTransaction.c.ornrnif();
. .
.

.
,

.,., :

. . .:.

Scssiofi.save(pZ);
..
. .

......
L.i.S?

.._

::.+.:?.

e.2 .7: .e..


.: ;,<: .>,.
..
'<<...
.. .. . . .

'

, ,

..

*.

'

.::..>,:.. .':

.-

. c.. :..,-,.

,.,.y
:
:.-.:

. . . .: . . . .,:,:.....:.
&a$..
. .........
. .....
. . ...;.*".<+
. . ..>.;
.
,
,
d
& .....
.
. : 'h.*...
.A*,?.

,.

-..-.

-..
.

.?.

..;.:<:,
. . .>9.
. . . :.
. ...:,.>.::-,
. . . .. .. .. .. . .
...........

.i r..

s.:.

.;).,,L...

. . . . .
' . .
.
;,;
7 '.i
;:,

..

..

;,

.: . :...:
. - . ..
. . ... . . .
. . ......

.-

$
;:

Sessioll.beginTransaction();
....

s:. ..
::";?s;..:. >.:.....,,;
.?,;.i.
?$:!.
,::.p

-.

. x
..:,<$; 3 .

..

In hibernate we can achieve twoI.m& of cache:


,.:... .'> >
1. FirstLevel cache.
........
;i: '.: :.
.
. .- . . .
2. SecondLevel cache; ;... :j . " "?'?:

,z
v:.-;

. . . :..
. ..
. .,:.. .

. .?. ....i,. :.!


..

.,

. ::.

..'

: = *..:

.:.:.

Cache means storing d$ta;;.hside


,.
a &m&h:,
and rvoiding lenghy
,>:$. 3 ....
;+ ,
...... ..,
: .., ..,.
accessing for frdquent uskd data. ..
7:

. ,.

'

.: .

......<...' .
.:

?$.:

;: ;: !

..*.....,..&... .

For this y+;dont need to set+xplicitly. By default d2$$$lget this cache


' .: 5 yt
'.. . . . .:
It store tht$ersistant object i&he session object.
. . .
It is available for only one user.
.-.$ 5
.
-A':+2-qT.
Inorder to manageghis,
use
the
methods
which
are
there
;nsr~,?&s+,son
.a .2,'.!
:.. ...
.'. ,.p.p
bject.
- q$i'.$+x.f.3?
,$&'.,,q.&..2
2.
?E,.li ?a:..,;
.,,>
'p .+ ..,
S o- ~
e ~ ~ e t hare
o d es~ i,.*,f~,:<..,..
&
$ .E-.;: :..: ~ $ ~tg.
$ $ ~.$.:;.~
.,: .:.
.:..:,,:.
: .<:.,~ & :..F s
..$,? :;$*F;:>z+;2;Fg::
'-. '. .,
. &v~~t(Object):It .i
.." , *&?$$$ . !if;$~>s:!&;""..,
.:s :$:+
&
..........
. < ?:+,
~to~mo~eaxpart1~~u1ar
Object.
*'..
.- .>?i:i$:$$:.:.j. f: .g.i9 ;
. ..:.
. . ,*....
>..
;
.
!
I
$;.$ ,.:,I. ;
;,:
..~
.,..+J ........
;
. ..:*-;:;
....
..
* . . .. . . . . . . . 7 i' ..:. i .
2. clew:.:yb
* . remove all the obje~tsl:~:,
. . . .
'

'<,

,;

. ,, . ..;

,:

..

...;.:?

(:

;%:?

.....

..

.~%-

..?..

xi

*<t. :

' *-

w.;

. . ,.

>

:
+

..>

,>

. ,

. .

+4,

,:..

.:

?. :

,& ?@

*>!Sk

?>

.i

. . ..

.*.

. !:.

y...

. . . ..

..' , c. , . .. .
. . .a . . .:. .. ... ..
": ;
; ' ,.,.

2) Seeond~evelcache:
*. ..
:;::.we
..,
will not get-this
.,-.:
cache irnplcitly. We have to setexplicifly.
.,.
-.
.ti:;:.
22.:
.It:s. t ~ r:. e the
s pe~skfkint
objects inside a SessionFactory.
. ."4'
.,, :;
:,t;p ".;
?
;%
,': I X
It is:;$iJagable
fofiag
the
users
in
the
sade~application.
!>
.T?;*~.,
., .;a
. 9.
Thre;&j'?e . . .. .. ~. e. v. e *.~ ......*
l ~ p p ~ n ~ stechnics
o u r c ef 2 k h .i.*e. v i n g this caclie,,
. . ,. ..
I E
~: ;: ' . .. ... ~. . . .
~
~
& . .. ..:.; ~
. .~_
......
. . .... .
~ . z T*.
'
. * :,..
' . :... . .
2. OpenSymphony ~ ~ ~ ~
c
i-..!
l
i
&
i
,
,
. .: .., .
.
3. swamcache. ::.,
. . .. .
;;:. . . .
. . . . . ........ . .. . .
...
4. JbossCac!~e. : .:':
.. i.,
Eli bcrnate s u p p o r t s i ,above
~
..
mentone&k@&fi
$ou@e cache technics.
Ws have to set explicitly;in the config file b':{&&tibning the cache
.
. .. .. '.. .....
technic 'fype.
Cache technic type can be m$$(fkd
. _ ,!
by choosing a suitable class f?om a
....;: . $ $ , ..
.;,;. ;!,,; . ;;'!
package ~ r g . h i b e m a t e . ~ a ~ h'ie:,j
,:

(;

. p,;v:

5i

yG.

."

, -,

>

,.x

:.,

:t.\

',

:
;

.,

F,

.:

-2;

[...

. .

L;

:..

,.

.:

, .

. . .

To set 2ndlevel cache,


Open hi berna te.cfg,xml
<property name="cache.provider~classl'>
Lsrrs Technologies

....

>:.

080-4 1310124

.~

..I.-

-:

. . .
.

:.

..,

,
+:

....:..
......

..-V .. .-.
.:,
;G
r

<;. ' .
.i.

.'..,,..:

..........
.

..

....
<.

."I,

:..,.f'
.x:

....:......+
L.

.?

......
..a:.

..
,:
...>..I'

' .i(uosauasa~d U I O ~pua 01 sloafqo l 6 ~ w l


elgp se Llpanp -3-a)l a h l uorlqgdde
.
Xue u~ksn 01 a a ~pue
j paq3qap
.
s . uoos
~ s v ; u o ~ s s a(arro
~ L~oexa)
aq IIIM
. Lay] 'pasol3 sr. uorssig.aw
ql!~
papposse r(puaun3 ale Laq~lqpis!
:... . waql
.
lnoqe 8u!$ p a d s dluo
...
ayl ' s g ~ ~ ~ u e aheu!pro
~ e ~ aaq{~.$$!,m
y_
&aqL
,
-uo!l~ut~j
ssauyq
pue alals jua1s!slad 3u1uyuo:,
s13alqo!p?p6aql
.....
alSu!s 'pang-~oys
.I

: .,

:.:>>&.

..
3

..

-..

:.

.:
.
..
:./

...

: s~aa!qo$ua$s!sJad

,-

<&adold />
a y 3 e 3 ~ g -qa~ ~ 3 - a ~ e ~ u a q ! q ~ 8 l o

Faqs

.. . ... .

. .. .
...

I) What is O m ?
..

ORM stands f o r ~ b j e c~elaiibnal


t
Mapping. 1t:s.a programmed and
translucent pe&ivei&ce.,..
. . . . . . of
.
objects in Java application into the database
tables usingthe metaditathat defines the mapping between the objects and
the databa$.:;~t
%+:- :.-. works by td!sfening the data from one representation into
another.
. .P(.
"
._.....
'-.
..,.
.<Z

<

. -.

..

.:.j:; 3;:.
;. .:. .

ORM is ~bY@it:~elational
Mapping which transforms objectsin Java,
-.
. n c ~the
. ,::.which is b a s e d " ~ $ ~ ~ Q ~ ~ z into
~ !table
e , of databases atidfor
. . .
this
:-. .!<>-!.:s'.-,.
.. ........ ;.:py::;
. :::,s.:t
\*..
she
mappings of objects and tables i n.
:::..:r.;$gt~;;;reads.the
..
. . . .
:..= metadat'dS@~;$&lias:gll
:< 2 : .
.daGga<$e....'. .<, ;'::.
......

:,

<:.:.

.i:;

.-

.:

.+....

,....M.?.
,-,:

?..*-*

. .,

. ....

;
.x

';

$
>:.,4
,.., ,..

! . .

2) What
:

j5

,bs,

:'

...

. . . . . .

'

. . ...
. .. . .

.: ..

.+,;

;-

..<.

'.-,. .&.. ;;.)

.......

,.

..:.

.:

. . . . ., . .. .

relational ORM? '

$jFe

'

::; 3i.<::
..,. '. :. ;

.-.
...........
,.-:
:. :. ;
$.::,,

i,,:

.>.

'

. . .

.~;:...

..

.>.<:. . ',..

. .* ;
.: ; .:

'

. m solution eomprisks:of?
....
3) ~ l &.f:_.,;.'j:".
d l o ..e san O
.
...
,. F...
,
.;.;. . .;.. ..;. :
. .

. . <

:'-...

...' .- . :: 5: :
!.., ..k. :,. ,: .

. .....

!
.

..
5):

It should h a v e : i a n : *f($ljer.forming
.~, . .
basic CRUD (Create, Read Update,
Delete) operatioris;on obje~t~,.~-f?,persistent
.>., .?.:
.
classes
1:
,.
.../ .

..

%.

'

:, .

..>.:
... .

:.

.. .
2
. ....

;.,,
. . 2,.
.:,.:.

.. ...

.
. ,:> :.,

Should have a languag&a


. .., %+.., an ~ ~ ~ f &. .<. f
. .k. &
. . ~ i :queries
f y i n g that refer to the
. .,. . ... . .
:, . <,:,:!
..... :'..
. . . . ..
classes and the p r o p &..-a%:i.+;p
& ~ ~classes
of
. . .
Ss

..:

.,~.. .:. ...:.,.5.:.


:a
....

'

:. .,i . , : .

An ability for specifying iriapfiing rnetadata

It should have a technique for O M implementation to interact with


transactional objects to perform dirty checking, lazy association fetching,
and other optimization functions
4). What are different levels of ORM quality?

Lara Technologies

080-41310124

,.

. ...
..:

' n e entire appli&tion,


..including the user interface, is designed
.. . . .
around the
:Rl:ational
...
../,..
model &
' b.......
indSQL-based
...
relational operations.
.. .

There are 4 levels defined.for ORM quality

The entire application, including the UI is designed around the


relalional model<andSQL based relational operation.
..

Light Object. . . . Mapping): .:


.\ .

11.

. .

.. . ~
.-

.,

The entities afcixpresented l a s s e s that are mapped


manually to the relational table~..Thecode is hidden ?om the
business logic using specific de~i&~~attems.
This approach is
..:
. . ..:.
i.: successi'ul forapplications with a 1ess:riiimber
.. I. .....
of entities, or
applications withcommon, metadata-dn\i<riil&
.. .:.?, ,.:
models. This
:.>..:
. . .
approach is most known to all.
.

.?.

<...

.:

'

. :.

..,,:

:,

.
.
. . . . .
.. .j. l. .
I

*..

-.

Medi urn. Object Mapping:

111.
. . .. .. .

.'I

. :...
,;

5 : -. .

.:;@
..:

, .

..

:.

.,
:,< .....

?l
.I.,
.

.
. '.

"

-""

;5-'---:-

.-

.,

?
..

.:-'.>.:'

~:>..:-b.,<:.

.t.:.ij-..:...q..
......

,,s..p*<~-;

<..>

..

-S .,iji3..2....Sr

.. . . . . ,.
. .
. .< . ,.k........
.;? .
,,y .*

:
.
:;:.:;
.>

%-

.... ?J. ...;


~ . .?s
?

..
;t

'S

..;

.
.

:.

..

1 .

.
..>::
,
..

.:,

'

;,.;

.,:

, ;.,. :uL..y:

Full 0bject Mapping

...

....
7

;-.:;:"j;
.>,.

'

....

..?.<.I..
:

,.:."

.. .. ..
.... -..: ,
. ,:.,

. .- ;
.' . .:,
..

Full 0bje?$&lapping ~u~$b&~,~ophisticated


~ b j e d,.~ o d e l i n coinposition,
g :''6.........
; (.,fi:;$?-.'
.i.$
a
inheritance, pol ol.ph i sm an~.$persiste~cece.
The persr~~nM~la$~;~~j:i~'
*.-._...
,
.*2*
,...:.::.b . :
.:. .
<
\:.
ks:
';.
any
.... "l-.....,.......
implements transparent persistence:
.-* pe~istent
.*. . ,,,;
classes
doa0t.1
,;-X. ..;.r..
'I,
g*
special base class 01-have.to implement special interface: Efficient
fetching strategies and caching strategiii'& ...i$pl'emented tiansparently to
the application.
:
:

e:

;>?

?.>. .

..?.,

.":
A

- :>

.!.C.

+. 1

?.

<..

'

.
..

. .

+,,; .:

.a,.5

. . . .,$
. . +,%
>.
' ......
F. ..
?.

..-

.3

'.:":.

".;%G:U;:
$.:,.".!.1.

.,.

The application.is;,designed
around an object model. i;h@'SQL
. . . . . . .. . . .
i-7 . ..::-.
- ....
<"dC is acneraied
,.., :;..........-....
at
.
.
.
6.Cifd.
.
.
.......
.
.
.... fun:e:;
.
And
.
the
association
bew&&$3,,
I.,;
........
,.,
.y ..:.
.. .. ..... . . . . . . .,:?
...
..;..s,-.-,
..;ii&!{:objects is s u p ~ ~ ~ ~. d ~ b y , .:;:,f i e ~ : . D
~
r
s
3
.
~
t
&
and
n
m
qucnes,
~ ~ h ~....n ~ m ,
----.,
.,<; ;.
.. 5. +L: t,g.,:
...
..<<?are..specified
using &';obje~~~~@~nt~dd:&x;p>ession
+.. a . . . . .la,.-.. .,R?r:+i
.... .language. %e2:ijg:z
;I-=.'. I...:
.
.':is best suj ted for medium-sized appq j~h@djj@@h
-r 4 :?S: .. $some c o m p l e ~.;..3?-.$ ~ $ $ ~
.. ....
+.,,,fh.+.
trahsactions: Used when the mapping exc~&X@&~different
...
'.Xi .fi>:;?
.
.
.,.:gdatabase products at a time.
i..e:.?
......
. . . -.
....

-: ..,..
...
;

.,

,
,

. .

.
1

.,...

r.r;,.L.
1Y.
q.r

. -.%
- .;. . .1,.
:!:

' '

;c:il.:...c....

..
.

-.
,:::..:

..

. . . ..,>-.1.'
...
>.
:? :,i ' ::
.
... :..:
. ... :..

...

..

.......
.:. ....
.. ..,...:
. .
. ...........
. . . .. .

. .. . . . \ .

5) Why do you liekii ORM tools li.l&4c.hib.egnate?


. ,..,,.
. . '*:'..
...
.?'
;a

......
.. ..!. ',......- .

,r

Answer 1 The main advantage of o m l i k e hibernate is that it shidds


&rn this, ORM provides following
developers from messy SQL.
benefits:
Lara Technologies

Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
Improved performance
'
o Sophisiicated caching
:
;;..
o Lazy loading
.
. .
Eager loading':
. . . . .
Impr?ved maintaidability
...
o A lot less code to write
1mpr.ovedportability
,

. . . .

"

>,

, .I :
.

,?.

.*

..
.
. . . 5.
5'

'

I . .

i.

ORM-@yework
.,.,.
generates database-specific SQL for you
.

.<

....

~nswe$2_:,
There are many'benefits from these. oljt$&hich
: . .. . . .. .
following Gethe
.
most
important
one.
...

..

. . .. . .. ...
. . .

i.

the

. .

...:.: r..'

<

...

~roti&%iiviiy
Hibernate reduces the burden of develbper
by
:;&$ .*.
. .:,i,);.,.$,s:;;:<::
+, :<.: :'.$ : . .
!> +:.
. . .y.,.%...
.$.:;?-p.,$
. ,.>, ;,gc-j,
. .+.;:p:;+ . . . .
-..:
.......
.:.:.,. k...
>,
-.-., <&;;;
providingpvcb;
of
. the
. .hctionality
. '.*. ..
and let the deve1oper;fo
....
.:.52:.. .
. . .. . ....
.
.. .
:
,
:r:y
c
o
n
c
e
n
t
r
a
t
e
:
~
~
f
l62iGs
i
~
~
~
S
1
~
.
. . - ;,:$.+.:$
.
,+; ::'
: _ . . . , , .2-'
....
.
.
.
..
,*:
,....
.
. ,. .. ...
.
. .. . ... .....
. ., .,
11
,:.?.Maintainability
-t'
i
~
g
!
:
&
b
~
f
j
3
~
~
~
,
&
most
G
i
d
of
~
the
~
.
. - ..
?;{.,;:.?.
.
,
'
v
<<:
,*:
.
.
.
:
k
:
..*.
::
.
.
.
.
..... .
.
-.. . . . .
': fii@tiona]ity, the LOC for.&e alj$&$i&n will be reduced and 'it:
:.
is-easy:.
,. to-maintain.By automated object/relatfqnal persistence
. ..
.... .: .
.
it eventeduces
the LOC.
. . .
...
. ._
....
. ..
... .~. 1 1 . Perfqrmance - Hand-coded persistence providedgreater
<., . ;....
?,5!5
;;:,
<.ti
perfoq.mce
.,. ,..,
than automated one.
..
But this is not tfule'.:all
.....
the
.......
:.:, ...
- ;:i..tim~s.i.B&in
..
. .;*. . .:. ..... hibernate, it provid&smore optimizati&!fiat
. .
;works
:ill thetime there by increasing the performarize.
,i.+ . If it is
. ..
autoni8;ed pd<siitence
. . then
.
i.t still incriasesthe perfbifhance.
.;.. :;.
g
iv.
vendor ,indepknd&n&&
-Irrespective of the3.$$fesent.
types
of
databges-that are there, hibernate
...
providesamuch easier way
. . . . .
to deveidp a cross platform application.
...
,.;:. . .

< ,. .

. -:\

.,z...,.,

:$'-%.,

.'4:.

#,.,

-,,,

.&'

'

.I.

. -..

A.~.;S;-~>,:

.:.
:

.
I

..:

, :> ..,>

I...

3;.

..

.;

:.

.<

I....

.;;

.;r...,z

'

,?

. ,-.
:-

. .

'

:i

. .

?.:...:

i * . .

.. . . .
..
):

....

. .

.i:-:..:.

. .

' -

:..
.

: >.
' ".
..

5--+*;1
. .

:,.

, .

. . . . .
...
.,
-

I.

.: '

...

..

,.

'

.
I

;r..'

1: .

\
,
.

. . .

:-

2..

' 1

2.

Hibernate is powerful, high performance object/relational persistence and


query service. Hibernate lets developers develop persistent class following
object-oriented principles such as a&ociatipn, inheritance, polymorphism,
composition and collections.
080-41310124

. .. .

--

7..

6 ) What is Hibernate?

Lara Technologies

....

>

-.

Hibernate is pure Java object-oiiented mapping(0RM) and persistence


fi-amework that allows you to map plain old Java objects to relational
database tables using XML configuration files.Jts purpose is to relieve the
developer from a significant amount of relational data persistence-related
programming tasks.
i.,

.....
-.
.......

7) What are the b e n e i. . .i. t;ni'.s ~ q... ..,.;,#:... -;~;..:Hibernate?


b~~~d
.+::.:St.r

\.

:..,7+-

..<a:I.
;L:.
.......
.
.... .<iC.'

:.;,?C.-

.. ,: ....
....
,.. '.'
i..!'

Productivity: l-liber~$&. provides+jildh


. .; of the functionality, so
developers focuses o&business logit ,:
1: \!
.
.
.. . .
Maintainability: LOC is very leis
~ e r>,..*~ 6 r m a n c e : ~ u. .;.t o ~persistence
ated
works f&
...... ..
~ ~ Independencg$;@asier
$ 4 ~ .... ~ for cross platf~&~&(Joes
....J!?. .....not depend on
. . . . . . . ..*.
.
:
.
&
,
?
,
,
<
*
,
.
;
:
,
...
+
.
:
.
,
any database.
....
,.: >
.<....... .
. . .
,. --

.v .+ . .&:*
:>,,..,

. .,

..

.?:

:.*a

>.<>

.>.L: >.

2->$

>.

. .

,2..ii8.::

-:i

:.,

<i
..:i

~:,',<.
.<...iF',I: .:c2*
? ::

. . . . . ..,...
.
(

8) What are the best practices for Hibernate?

......;... .; .
1.
-.;:
. ... .. ...:
>:
i

'

i:

.:

(.

...-. >"
;:,;@;;:,? ,..,...*
:.. .. ..,:4:c,
..r:.j, l$'i::A,,
1 . . ,.:.'I zr:.?.,,
Use
.,, . . % . K , . . ,
.;;. ,. '.$.;.-..
. ,. . . . . . ,:-. . . .
.:.
<.

.....
.. .. .. . .

i.
., ....

.
.....
.

:5,..fi.;

'

:'

-A:,

?.

:' .Y

3 .3%.

?.:..

'.fi..,$ :?

.;

. .>

:?r

; .. ..: . . .
. . . .. .. . . .. . ., .. ..:::;.. .+,. ?....,:A>. . .?
. ...
.
. ..:;. . <:.,. . . .""
. .. ..z..: .x:.,'i; ;
:
:
; ...;,: < . . .
. '......
. .^': .. 4):
.
.
"
3. :"
:.:<.:. ?
. . ,..:. . ..... j,;,ii I
>
,. ; T , .
:<*,:
-.l, .... _ . : ;
. . P. ..
!.; :

""

key

'

lrnple&ent $el-ializableinterface, usehl wh&imigrg&ing


..
to multi. .'> .,.- 4..?..?...2.
*.
$,
%
*:
....
pl-ocessolcluster:
< .{>Z).
. . .
.j>.>.,->:.

;
~
?.
..
. ..,,...... :
:
:
.
:..-....:<
,; .: %
, .,,,

4.

'

',

& a ; : & a s h .tjGti,don'tuse id if th


a.j:...;-

.."E*..
J+y, <., . .
. :,.. .. .

. . . .;. .. .
,....,
c.:?
, .- ,
....%

>:..
: $ ~ , ~ y +.,- .. !:
. . . . ..*. 5. .;. .;
.-

. . . ..,*
.*
.?'&

,; ..', a?,
(

.:;,;! :f?ey,,.-

. . ,,.a&<:+>.;
. - l . . . C.\,C 1 . <
. .
...

$
a
:
&
;
:
.,
;
.

::$;rrnfirernent
......
:

. . . .:':.

-...:I
l,

JavaBeans

. :.

.>: . .;. .-,.: .: L?:,.

2.

.;

, .:..:,.,

I/

&

::

.;.., r.., *

.. ?. .....
. ...
. ;.
.:,:. .,.,,7.

.:

....

z+..ik:A',

i@?exsistence
class should not be final,...
.-,....>..,.
...ih;.:..
*-*
<.+.
.
'3 'i.
C

<..

.wa.?..
:

$.%
.,\$$

,;.-

-.

,ll.ki

.,

_
.

$@ j;:.
ti\-;.
I.,
..-. .
.?

' '

,,:-+

'

. ..Ah.,
. ,.
:...
: ,.:<::.!2$
. .*-I-j>:.

-::
........
?.,r . .

.:.
-...,..
.;.....
.:.:..a .
.;z:.v :
?.

'

>

Lars Technologies

?,$.:;

,.

:... ;:.*::

:',:;!

.. ..,,.( ..:.
....

'

. . a, ,?........I.......
.,)
< :.$
.!.;<:,.7 ;. :*. .... '.>!,c
.. I . .., .. '
? :; $

<... . ... .::.. . . ,.4.. .:..


. .: <:,,
,. $;':
: \ "'
.2:.,i..*

......
-

,
,

A:,.

, . +.$.;;Al4;~:.?).

.: ,:.,:..
.,:
:,
-.
.:,<.:>;2::
:.
.....
.
.
.
.
.
.
. . !;..'::.:
.-; '<..;:;i:$:;:.
.<;: . :
:
L*..

::.
..; ?,..j,:
1;-.,.' ...:...
;,, :: .;3;:*:.+:e.>&

:,>.

.
. . .. .<. ...

. . ,. .
...;... ...<,... ; ...
. . .. . . .

-:
;,..-1:>*,y:.:
5$@3:::
..%:.
.-.,
r .;:

.... , .
_. .. . . . . .
...
:!.::;j,,:!.

..T~+Y-

Ya.2.

..

,: ,

.LC. L

<.

. .

....

.?.

?.:

''1

.. ;: :.,,,.:,<.?
.z...,. . .
,.
, ?%

:. . 5 ' .

.:.-5."$$ T+4 ,....


' ':.,&',;.~Y'h
.:. ;
;,x .? &S . ?
.....
.. <+'.,...:,..c<?5;. . "'
.
.
.
I
;
.
. .? :
. .
..,,
J

.,>.A&.
;

<<.,?.

< T"

.$I

,, ..
:

,
.
.....
:<
"

*.
.......
,'

. . . . . .
. .

'

. ..: . .

9) Show Hibernate overview?


.

..

.,

Business Layer

a
Life Cycle

?l..
'

. ....-. .,<. ..?


.. .... .. . ., ., ). ..:...
....
'* ....
..,.:
.'!\.
. .

.- :......

"

Persistence Layer

.%

%.

i;ljnne~:ted using an Illteriept~:~r

. .

....

!<

Classes

. .. .. .
.......
. . . . . ..
. .. .. ?
.:.,, >i;: .F.y :..!. <:.,

;.;',:.?!c$<+:,y; .. ;:; ;
. h,:.
.: .
.. .-ST',
. . . .:.:. :' .2.* -,

.cfl
1

I
E I

Session

SessionFactory
......
. . . .

. . ..7L
.....

Transaction

.:%

... . . .
.,,. . .
..
?.

a
Configuratio

..

....
'1. T

......
r

,,

;,:

, , ; .

,.

. . :

10) What are the advantages of Hibernate over jdbr?


Hibernate Vs. JDBC :-

, .

'
.

JDBC
With JDBC, developer has to write
code to map an object model's data
representation to a relational data
model and its corresponding database
Lara Technologies

's:

c .

Hibernate
'

Hibernate is flexible and powerful


ORM solution to map Java classes to
database tables. Hibernate itself takes
care of this mapping using XML files

so developer does not need to write


code for this.

schema.
.

::

with JDBC, the automatic

1.

of Java obje,cts with database tables


...
and vice versa conversion is20
.:.. .:be.."'
taken care of by the developeg:
manually with lines of code;.
...... .
..

, ...

:.I:

-.

'

.
... *.,: yv. .....
.., ..*y+:::.:.

. ~ . ~ ~ ~

... :,h..&
>
: ,..,,*
~......

:-,:*,a>,
c .,,r
2
:,..:I:

Hibernate provides a powerhl query


language'.Hibemate Query Language

..

persistence and developer does not


need to write code explicitly to map
database tables tuples to application
...
'objects during interaction with
RDBMS
.

*........
JDBC sup~otisbnl
y native.
Languag&@QL).
..>..:.
Developer fia$. to find out ther$
efficient way$o access database, i.e.
to select effeciive query from a
number o f
to
. . . perform same
::.

'

::-.:. j-abernate
.,.
provide's transparent

(independent:.from type of database)


that is e ~ ~ r e s $ &a$ familiar
~
SQL
like syntax and idbfudes full support
for polymorphic queries. ,fibemate
also supports native S ~ ~ h t e r n e n t s .
;:
It also selects an efGectiv$#ay,to
.....
...
.
~ ~ . . . . .p,erform
. . . . . . . a database manipuiat{6%~ask
. . .
. . ':
.
. .. . .. .. .. .
.......
., - :+
~:: :i.?:
~ >?~~:f&si:&
~ : : ;application.
.....
.
. . .
.....
.............

....:$$::i;,,:;:
.......
......

.+..

>

..

(.s'

'i : i

. . ..

. ..

., .. .,..

. .

.:,

..I

.;f:

.... . . . . ..

ij..

....
. .....
:?:.: . . ..:.... .. . . :.:. . . . .!,,<.
.
\...
.
.,.:
.L.,

ing JDBC to handlei .i;>1.. '.' i: ,. {.,.: 1 . . ..:-.. .


,TI
...
. . . .. ;. .. .. ..,. .
(database tables)
. . .
-.,.;->;.-;
.
k&i&&ing
s ...databasb:Specific bode in
... :.. . . .
'*'
%q@guL*..k..-"-$
egimount. he &ode written to
~ i b e m a t providks
e
thi$:mapping
. . .
:
%..**%
. .
m
t
a to a P l i a t n objects itselr The actual 1napplng:between
table? and application obj$:~tsis done
and Vi :e -rsa is a6t&ily
to map
. . .
in XML files. If there is change in
table fidq%:$.:objeitproperties. As
ata abase or in any table then
...
the only
.. .
databasecb-qged
table changbd:.or
then it's essential_to change$bbie~t.~:?~,,~
":,$ .:..
...
. need to chang&.~~~,.,file~~r~~rties.
..........
.:
.
.. . .. . .. . .. ..
.,: ,. ..... . . . .
structure as well asito
. . . . . .change
..
codki2
3,;. ,,:_
..........
:
.
.
written to map tab]~ - ~ o ~. o b j ~e<t-<
c ~.-;$
jsf;)~'
o .ab,.,.;si.I
j. :2;
:,,, , :;..
;.......
..
.<,:
;\;. *! .,J.
.' '.
::...*
.\
,; .:.,;:. .;
: . .,..........+
.....
to-table.
...:
.;;;. .... . . . - . . . .....
.

,%

..!&.:

'

.,

.
. .:-:

.
. . L
.
,.

..,:,

..

. .,

;.,

:,.

...k.,7k.

'

:
.

, .?

v .:.
..&.
....

.i.

i
'

-!%.

:, ,
:
.
T
*
,
%
.

........
-y:~i..".:,
<
.,?
..:

'

;;,

..

..;.;--

C ! ' . ,

..

7 y . . . . . ~

,,:.;
.. . . .

.-;

~ i b e r n a kieduces lines of c d e by
With JDBC, it js deye]opei?$i!2.:..
,,
responsibility to handle J D B C .<. . ~ ~maintaining
~ J ~ ~ object-table mapping
set and convert it to Java objects ;:.:.:.,:';;.itself
and returns result to a~plication
..........
through code to use this persistent l::i$in;forin
of Java objects. It relieves
!d.. .,;*, **::-.
.: .:.:
data in application. So with JDBC, ?;$p$ogrammer from manual handling of
mapping between Java objects and ..{.$$ersistent data, hence reducfng the
development time and maintenance
database tables is done manually.
c .,

...- .

...
.
.:;!y .
2 ,

::.<.gi.:y: ,

i
;.
'1.

r.-&

Lara Technologies
1

..'?

., .
.

Hibernate, with Transparent


. : Pefsistence,
cache is set to
.
application work space. Relational
tuples are'moved to this cache as a
result of query. It improves :.;
performance if client application
reads same data many times for same
write. ;~qtomati
.,,.g x
c Transparent
~ersistengeallows the developer to
,:.,+:
- .concentrafe.@ore
,,,.<> la.!.y,
on businesslogic .
rather than'this$:Bp
:.? :.,zf.:2$ lication 'code.
:> t.3:'
,:'*:'
......
:*: $3:
Hibernate enab'l&id:!eloper
to define
version type field"~d.&$pljcati~n,
due
to this defined field sHi$gy*ate
.;
. . .*' :. . .

With JDBC, caching is maintained


by hand-coding.
.
.
.

.
.

.
. .

.:

..

A..

,.

";

.
.. >. .. .
: .:.

:.

.'

. . . .'
...

. ..

...

f:;$-+:

?
:;

...

. -.. ., .
..

..,

updates version field of'dqg.&y


tabls every time relational 'ufi!l$s.
<
,<
.:%
' i&$dated+,in form of Java class ~ Q @...G $ ~ .
In JDBC:there is no check th''i1- :.: - : ,i ;>.. : ;,:. ,..:; ..
...>?.$! ..:
.. .'$..tQl
~ a g : b b ] eSo
, if two users reme$&-$$,.:
.
'&.;
ys every uSer has updated d&j. . ;,y.;c ?
;i;: ,,: : ;<
s ~ ~ ~ t u p ] ~ modify
~ & & it
e and
n
.;, 4 5 ,,...id::,
his check hasib
bi added by the
.:; .
one user sa$e.th@fmodified
.
.
tuple to " { ' y
. . . . :;.:..:..
loper.
....
.
... . . ..
database,
v
e
r
s
i
o
~
~
~
~
~
$
~
~ t o m a t i .....c a l l y
:.. '.
::
:
updated for this tupl&$$.&libernate.
2.~,*
..
;&,Pb
.....g,.;;
-, .,.:
When other user tries'&.,~aveupdated
:
.
2
.<.:.
:ilpl&.todatabase then i t
not
" , .
....
.
..
allow &i$ng
it because th&bser does
', i;.
.
,?.<. :;,
.
.
-.
have i$&ted data. .,. . .;%
.,:,...,
.
.
.
. .!;
.

.
. . .. . ..
..

- .

..
.

.; .:
.,.

.;.... .. . . . - .

....

. .... .,
.. ... & :

. . . ..

:. ..

+.

:G

L<:

+ :

...
. . . .s

L:

3'

..

. :

.c .:+

.$:>a.

$.- .-

.5 i:

'

tt.,tz

i . .-;.I.
. . . 7.;

.>.. p: , <
.>. .I
>

q<><..

,:,.!?,.

< ,

-.*-,
::

.i'!F,

1:

...

. " r :cF'
..
... )

. .. . ... . .

.
,.

. .:
r

.......
I.

.
.

..

'

-:.

il.
. ./I

.<.,
. .

.2<

<

...........
. ,:. ..... ..,. . . . .
:

i::..;

. . . . ..

..::.?..:.,
.... !.

,..;.:
$: .
. ......
.'.?-. , ,>
.-<..: -;,:,.:.
..
.........
-.
,,L..........- . . i l . .
G

: . .. . .
.

.,.

..

, :..

.- ..;.r.,
. . . ..
. . ............
..I.
,

..:. :

: ;
,
. . . . . .j ..
; ....;. g.:?, ,j;..:
.:;<.
-i:. 4 .?.......
........
:- .
. ,,,. ::..- ..
;'

r.:.

. .'

,.':

: x: ,:.<: .:;
: ,,: :,:>,.

'i.,

. .:

I.

.... i..

..,.: . . .? .

11)What are POJO~?


'

POJO stands for Plain Old $ava Objects. These are just basic JavaBeans
that have defined setter and getter methods for all the properties that are
there in that bean. Besides theyican alsohave some business logic related
to that property. Hibernate applicati6hs%vorks efficiently with POJOS
rather then simple java classes.
12)What is object/rela tional mapping metadata?
Lara Technologies

080-41310124

136

ORM tools require a ~netadatafom~atfor the application to specify the


mapping between classes and tables, properties and columns, associations
2nd foreign keys, java types and SQL types. This information is ca!!zd
the object/relationa l mapping rnetadata. It defines the transformation
between the different data type systems and relationship representations.
.

.
.

13) What Does l3ibcl-nat<sirnp1ify?.

.-

, .:I.....
.....
.,

Hibernate simplifies:

.
.

. . ..

..

>

.
.

.
.
.

'%. "

...
.

Saving and retrieving your domain objects


Making database column and table name changes
. . .
.. . !
~ e n i r A l i : ~pre
i n ~savZ2AcJ post retrieve logic " . : ;.. .
comp1'&
. . . . joins for retrieving related items

-.

<:...

. Schema creation from object model

......

.
-...

.....

<
.,! ? :

..

,.

,.;I::>;!

,.

r<

<-.

>..

..

!>:x'?

..I,:..

:.>::

..

,::;

: :. ..

?.!

.!.::#;

""I?..

,:,,, ;:
:

'.

;. "?.
*
...

. ; .r%..
;

.,,;

::

;.
_,.

:?.;< !

-1.

?..

..

>

The filen$me;.varies here. The extin.si&iof &$e2, . .fi~~'.~should


.
be ".hbm.ml'.'.;$
. . .> .;:
is just a c6nyentioil and it's not mandatoiy:B~t;~thlsiq
.....
...
the best practice
);;:!::This
.'.
,;.tofollowthisdxt~nsion.
!:. .......
:.:
. . .
. . .
....
.
,

,-*

.t:;:

a.:;

,:\..:

?,

.>,

?!

. ;.\: <.

7-

:>

"

.:c...:. . -..,:....:.. .. .. .. .

-.

,,;:

:.?:..\.::>.:

-3'
'"

......
'. ..
.< . .,>,., 9 :,
<.
. .?.

-,

.:.,
......

.... ..,--,
si :

13'.

". .I
+

. .:
.
.

.-

::

:
:
.,..* ,.. :, ..
*..:
.> .,.:;.*..; . ..:,*-.,
. :. :.,: -,,,..::

'.'
85:!22 1 ) ; ~. ,~%;,<.:$g:\
h a tis the file e~ten$$@;~.ou
$se
for hibernate mapping fil&2j;:s:.;,
:.,.
.......
. . . . .... .
.;
. . ;.. .\ .. .
.
.
.;. .
.:
.........
.......
;..
.
:....
:.....
:
.
.,.
"~.
:+;j.$gj<;,
p;;;;>.:::.s
$:.
,
:
..f.
!
;
:
;
;
:
;
.
.....
...
.-..; ,
.<..,. ...
".
_
. . ...... .x
.;,. m l
The n&@i5fthe
file
s
j
l
o
u
l
d
'
~
~
~
~
i
k
e
~
;
~
s
~
:
,
.
~
.
f
j
~
~
n
n
~
e
~
h
b
m
...
.......*,..*
... .*....
.:. .,r .
'
, ;. .
;
.
".,,.*. - < . ..
. ...
.

.,:

.:

,.

,tt..::: ...
".<.
..>. ;..

. .. . .
. ...a.
..;

,.

.
....
.. . .
...
.:.

. .. . I%.+,
:. ...;i. .

... ..,>-:...
'..".:,:%
"G.;?
> z , ,<""
.!?.;,
,

.
.
. . .. .. .

15) Whatpthe
,.!,!.
:..:.
peed
.
for.:Hibernate
....
xml m&iRing
file?
(.,
'
. .. ..... .. . .

..

..

...

-*;.$%:.

.
. .....
. .

.$&.'>,
.$&;&/<"

. . .

. .. ...,...I... .
. .
. . . .. .
?
.. ..

Hibernate matping iile tell$B&emate


..
which tables andcolumn~'fo.~use
to
.....
.... .,-. ... -rd ..
load and store
Typic&~*m$j&~hg.file
look as f6lows:, :;:i.
,

. .. . .

.:. .

.;..?.
L.,

..7.:..:<5
..,,
: !.,!..
* ...

'

..';i:;.

:..

,;.:,

....'.?f,; !9;,;: .. ,.:,.- . ..


.,,
y..
..:

, , .: :,+

..

'

~.

Lara Technologies

'L

. ..,
. ..

:'.

:.
. . . .

.....
....

:...

..

. . .
.,.
...
.......
>

,;. .,. .:.'. :..


. .
.. : . .<.::..
->>.
.

. .
. . .. : .

.-.. .. . . .
..,:..

.,.e
..r..,
.....:.

There are mainly two types of environments in which the configuration


of hibernate application differs.
i.

Managed environment - h t h i s k c d ,. o f environment everything


fiom database connections, :transactionboundaries, security levels and
all are defined. An example
...
ofthis kind of environment is
...
. application
. . ..
servers such as Boss, Weblogic
environment provided-by
. .. .
and WebSphei-c.. -1....:;:;' '
. . . ..,. .,
Non-managed envikknment -This. .kjnd
. . . of environment provides a
basic configuration te'mplate. Tomcat.isloneof the best examples that
provide this kind of enviionrnent.
.

.. .

i.
..

c,bz.i.c

I % i

. T.'...,,*$,'
. ..

,.

:,,.,..!..

?' .

.-

.
:
.~

'

>.

J..:

. x

.$.;>:.;:,
. ...
....
........

.
*,;.,*: r7
18) HOW willyou configure ~ i k rvi..n a t e ?
* y;:? y .;
The configuration
.
files hibernate.cfg.xm1 (or hibernate.pr6~;.&ies)
- . . and
mapping files *.hbm.xml are used by the Configuration c~ass'%b:;t$~iate
.
(i.e.
+:...,
. and bootstrap hibernate)
.:$...-.i:kppcd
,
. the SessionFactory, which ht@&deates
vi;.;;-.
: configure
. .
:. . the ;igg>.,.
n instances. Sessl$in;;mstances. ere-tbsprimwy
interface f~d;&i.,~
......e;;?...;:,
., .+'! . ,..:
;;<;*$*, 2 ',-':~*:p:<,,~:
.. :':
:.
,-..:-.. ...
....!?::;,...e .ys:$:;i.2< 2
..v
.-..
.,..
perslsf&i3&
service.
:
A
:
!
.
+
:
v.:
......%;:-; ...--a ,:....
.,,-:
.::.,
.
,&::
;
,.,
....
-+gg3,;
:
.....
....::.
-..
..-..,.,.;. ...,.. ;;;:-.+,;:
.; $!.
......
-<-q&:
...
....*.&y&
-.!<.;:.;.>.:;~j;L~%. :fi;:;,~$~".'.
&<. . ;;.:.k
. L..
...ti7.:
".*$
..; ,."
$;'
, .rr.,c.r;j$..'-,
,
r.....
:c :.
<,;:. .-, ' i d b '
.>.?+%>,g..
hibemat$c fg.xnll (a]tematively can use -hl~~@,ate~~li~$A~fiies):
These two -'%&;g$:i;.:> ;.:;
: ?: .,+
.,
..........
.:,..!.::.
.:
es are used to configure the hibernate sevice (coriii&6$@n:.driver
:, * .:
class,
ection URL, connection username, connection passii0d, :dialect etc). If ?:ij.'.....
...
"
both gigs are present in the classpath then hibernate .cfg.x&l'?fIlioverrides
?,??:z$\
. ......
.7-,;,
....
the s ~ @ sfaund in the hibemate.properties.file.
.:,:.
:.. .
...
-.qggi:.
: .,
'. .
,':,.:
. '.'
;$$,. .:. .!
~ a ~ ~+,, i... n(*/hbm.xm&
~ l e s These files are &6gt!p map persist&@objects
.?-.:
.. -..
to a relatiorialdatabase.
.
.
~ ~.:%
i ~ ~:i3.':,lF2.,iebz.. b e s t . ~ rto
a c&&e;each
t i c.......
e
objec~dian
. . . .:..
. . ..
. . . .-;
. . ...*.
. :. ,:
...
individual mapping Jile (i.e'~ifiAj5$$ig5fi1e
.!
,
per
class)
beca~~e_stomg:large
.......
...>&i"
..
number of persistent classes intciC8fi+pi@pppigg
file can bk@iffcult to manage
i:$3 :I
and maintain. The nai~~ing,conventio~~~~~~t.o~u~e.
.:'..: . . . .the
. same name as the
;.&>:< .: .: persistent (POJO) class na&.
..:.=.
..., ..... or exam&
Accppn~.cllSs
...
;..
will have a
mapping file nanied r'~ccounfi$bm.xml.
...*::.... .
Alternatively hibernitte amotatiofis
can be used as pal? of your deisisfent
... ,..
... clnss code instead of the *.hbrn.wml
.........
..
files.
.....;.*.
".>c:
$:k:s!::j:,..

.s~.2.:.+,2..t <.

;<:

:.

;.

,%..

<f.:r2:

..,.

f!

. .. ... .. : .

.-

...

. . .

,.-,=*:

:;

:,;.-

":

J,-

c:2y;.+
I1~,,i:l,.:.i';i;"'

..

;.;

.',:

'$

<. ;

.:. . .

v:. s ;

.<> :

>.,,

:.

..

'I

'9

\;

::.:%
::

.-

7.r;

,,. &
:?.:

&.$

;.::

>..

>

:.:.

;a

.-. .

?&:...

...

!;ycz,;
.:,-

.G,

': ' s .

,;: : : ;; ...:. . . ...


..........
. . -,>.! '.>,.,....
.i
C' :
.

......
. .

5,.

.: c:, ,:,..;,<

u. :>

...

.',.
.;:*;,.

' . . . j ! .a:...,

...........
. ,. .. ..
........

....

.,

.,:*.-

19) What are the most common meihods of Hibernate configuration?

Lara Technologies

'

..:,.

?.

. ,
2.L'.

.?.

,
:

:.>

e,-::.:

.c

*:?.

-.

,.:. .,.

..,

=.

h ttp://javaeasytoall.com

The most common


.
methods of ~ i b e m a tconfiguration
i
are:
.

Programmatic configuration
,.

t;

,... .

,
;

_. ... ./
:.

;.
XML configuration (hiberna t5e'.;;cfg . xml)
.'i

'..

.:

. - .

..

i .
2

, .,

.i. .

. . . . .

Method chain&&$?.
. 5x
a p r o g r h i n g technipue.:that
is supported by many
(;. '.
.;: ,.u.
;*,.&.*%
ae&.:,,s:
is i b s readable when compared to actual java
hibernate .inPe'&a~@~This
e+-.. code. &fi;it is not riii&tory to use this fo&;t. Look
" how a
sessio&ktory
-.
<.
is ~reat6d'~hen
we use
-- --- ..if.c!-.&+-*,.;, $?+?.

1.

i.

2"

.-p.>..i.

--

. ....; :i;.

Sessio&a.ctory sessions = new Configuration()


-.

..

. ....
.

. .

.. ~. . .. . .
':
A
:
.

'

.:

'

..
. . . :... . .
... j

s.

_.

..

* First w@$&.d
., :rs.F to write Java domain obj'$<tf(beans with setter and

.:.

....$
.:. .:.

,. . :.,.
,?-.,<'I

: %.

y .>

..,?&?*.,

getter). ~ eF,zsi
@ r,r i a b l e sshould be same as databa~e~c~lumns.
..........
-;.. . . .
. .:ii.;i..zwfite
-..
hbm&s.
where we
java class to table &d..database
+?
.:
tz*
. .
. .
.-'-9
.cc$lurnns
to
3
-;&,class
variables.
r
.
~

. .

. ......
. ..,: :...

.,

'

.*.2.:-+

,i

'

Ji?.j.

G;!+:

. ;.

'

:.<:;,+.

@+pi;%

.-'!

>$?.?@
.:

,:

..

.>.

<..,t..

Exampl&f
. . . . ,.
. .-

*, .x.+:.

'.

..

.. .. :.
. .

..

s;'?

:;. t !.:';-?
, . jv
:.ti.. ;.
jjG;;..;,
.

.;

. : .. ..

. . .

,""'

..

>?

..Ck..+7

:.
<hibernate-maming>-:Jc,, ;
::: .
::.
. :;:;.,$ ,,\
<
.
A,l"~;.
<c I ass name-~+.oo.p.
...
.:. ,test.Use~::-tab:le="user">
"-;j;i!; ,,
.' _
<property col'lmpk,,USER
..-....,.J;
-~ ~ ~ @
. . . '. .l . e n ~ t h5"
="25
. .:" ..
:.:., ..p:jJ,...,
name="userNamg -not-null="trukk::type4ava .Iang: stringt'/>
<property c o l u m n = " . ~-~s ~~ ~~ ~ ~ 0 R d " ( l i n ~5"t b = " 2 5
name="user~asswor&!,
n&:null="trueV
.
.
typ&=ttjava.lang.~tring"b
;.
</class>
.. .. .. . .
.:
</hi bemate-mapping>
: <
:

. .L

. ot

,. ~.?-,l::.:;
.',A

I.?..I.

.+

..>

.L

,.

. )

..

: .~

'.

23)What are the different methods of identifying an object?


Lara Technologies

There are three methods by which an object can be identified.


i.

Object identity -0bjectsare


....
.( identical
.
if they reside in the same
memory location in thefm.,This
can be checked by using the
..! . ..;:
. . ..... ... .. .. .
= = operator.
.....
-;. <..:..:. <.>
Object equality4-@bj~s
,& .:,:. :;+: .,.:.<: !.>;.:
are equal if they have the same .
value, as defined&y tbe.$equals(
. ,........
.:,.:
) method. Classes that don't
explicitly ovenid; this'm6thod inherit the implementation
defined by javailang.Obj&t) which compares object identity.
Database iderdtity - 0bjects.ti6red in a relational database are
identicel if they r&r~sentthe samerow or, equivalently, share
the same table and *&mary key value.'
,'

i2.6:.

. . ~.
. . . . . . .s
. :.

<,<,

ii.

iii.
:

...
.. .. .
> .

:r...

2Q)What are the different types of property and ~ l a s s ' . r n a ~ . ~ i n ~ s ?

/..:..
. . .. .

"description" type="stringU>
="DESCRIPTIONn/>
>.

..::.
:'

-.. - .

..r.i9..3

-<:c

.+A+r.

...

...

.. .., -.-

DerLed piop&ies .......


2$$>~:.:.j;.,
..
;?
.;.:,

. ..

...

.,..

.. \T.$'*;>

'
......
. .

. .. .7.

:<i:j::~

.'*;. ?.......
;:;:' ,*.::
.-'
L.*.L,

i:
,

.. . .

..

'3;,2$;.5"%...
. : ..
.. .:..
.
....,,.:.....

<propel-ty n ~ m e = " d e s c r i p'r+,I,.,:.yit :i.: o n... ~ ~ ~ o f ~ ~ = ' l D E S typ&llstring"/


C~PT~O~ll
.:<5

?<, .?:

;*, .,;
...........
. . .

.!',

.,;*. ,!.,;.

:..::.
:.'

,.: .:

Controlling insert-

Lara Technologies

080-41310124

14 1

<property name="namencolumn="NAME" type="strhgn


insert="false" update="falsen/>

5
Y

25)What are Callback interfaces?


These interfaces are used in the application to receive a notification when
some object events occur; Like when an object is loaded, saved or
deleted. There is no need to implement callbacks in hibernate
applications, but they're useful for implementing certain kinds of generic
functionality.

26)What are Extepsion


interfaces?
. . .
.

, : . ; >.<.

:..

,;a..,

. .>

When tdeuilt-in functiohklities provided by hi bemate is not sufficient


.
enough, it .provides a way sothat user can include other.interfaces and
implement . . . . its interfaces for user desire functionality. These
....
interfaces
. .. . . .. . ... .
. . .. .. . .
are called as E3tension
interfaces..
.: ..-,
..?+ .

ease

;\

.i

>.

..

.
..

.
.

'T

-+ ....... . . ..:.:."'
....
'

,:-

. . ..

...

7 .

. :.

>

..A.

'5

. <.

.. . : j

-_
;'

:.-:.
:: t.

. .:

.. .. .........
. :, .>
. .:. :. . .

. .".,. ..:; .
I:,. ....
,< .* ::; ?
:>
. ......
S

,. .:
i

.:

..

.. .'.

<

::

.....

~ .~.:. b x ~ ~ ainterface
e t o r- ~
used tb ereat&pidxies
...
ConnbtionProvider
interface
- used fori'JDBC..connection
....
.'., ,.........
,,,,.
.....
manegement
. ..
.
~ r a n,z:&
t
)
~
~
~
a
c
t
interface
~
r
=
y
Used
for
trans&ibn
T: ;:
.
'::
:
manageMent
.
,
~ r a :.;,n .+&
:.), i t i ~interface
n..
- Used for transaction rnana&&ent
Tra$$h%ii~$ManagementGoku
.
...
.:*..;.
..,.,
P'herface - used'*,...
: :_._.
....
?:.*'..:.
,.,'A:!:...
,.
.
trdri$kction
managehent,
._. .. . . ..
.
_
.. :. . ;. ..
;,, ::.. . . . . ' . . . . . . .
~ a h e e b t e r f a c -prb,vid$s
e
caching techniques and%trategies
~ a c h e ~ f o ; i d e interfacer
same 3s Cache interface
~ l a s s ~ e r s i s tinterface
er
- p r o v i d e s ; ~strategies
~~
Iden tifierGenera.t,or
interface - ~ s s :for'primary
d
key
:
. 'i.
....
generation
.
Dialect abstract cla<s::- provides SQL support
:,:

,.

.. .

..

..

?:.?

.
,. ..... .-.
.

;
..,.:%

There b e many extension idterfaces provided by hibernate.

<;::~-.;.:~:;$7)What
are t h e:.. \. . . ~. . . ~ ,,.t: :I. &. .~ . $ i ~that
~ !are
i ~there
t ~ in
~ hi
f b&.n+;tg?
~ ~ ~ ~

c..

......
. . . ., ..:
7 .

!,V

... . .::.
. . . . .;.i.:.. ..:. . .... . . . .. .?...,...
-i
, ..
-.:*.
.,... >..
........
. .

..,:..

:?:.<

...

. . ..>. .
:I++.
.,."\.,, x
-.$
,

,-,

39;

'

~%,.

'

..?.

.... .. .
. :..
.

i.

. ..
,

. .
... .-.

: .:A,f:
.<.I:.

.
'

:i

,L'....

. .- .

. -. . .

.2.;

..-,<;

':'

!+

c...:.

:A

..::.

..i

"

>. .

,.

.?.I'

. ,,,; %?

2-

,.LV*.

.;

.,I

!:

..

.
..

28)What the Core interfaces are of hibernate framework?

There are many benefits fiom these. Out of which the following are the
most important one.
Lara Technologies

080-41310124

142

Session interface -This is the primary interface used by


hibemate applications. The instances of this interface are
lightweight and are inexpensiveto
.........
create and destroy.
Hi bemate sessions q-+$i&bad
.......... - ...
safe.
ii.
SessionFactory IntSi.fa&k
,.:,:.
.....
- ~ h i 2 i s .factory
a
that delivers the
session objects:to:hib8kate applicahbn. Generally there wiil be
a single ~essio&.a&or~;forfie
. . .
whole application and it will be
.-.,
shared amongall the application
. . . . . .
threads.
iii.
configur:ltio<$,nterface -;m~;inierface
.,-., ......:'.;;
is used to configure
.-..<.
...
and bootstrap G&rnate. The lnszinne of this interface is used
by the application~in.orderto specf.@'
ithe
location of hibernate
....
;
...
. . .
.
8. specifir inappingdochents.
....
- This is an optional.
. .
interface but the
- iv. ' Transaction 16terface
,,..
. . .
.
.
above three interfaces are mandatory in each:.,and
. . . . every
~ a of
n ~
application. This int&ace abstracts the ~ o d e f i ~ kind
transaction implementations such as JDBC tra&&tion, JTA
..
transaction,
. -.,
' h ~ dInterface - This interface al]ow$the user
. ?.-. ',..... .,-.:+;;*.,v ~ ~ ~ $ Criteria
.:f.y. . . . . . .,;<....
. .: ,',!:',:;.::.
:. ;.$;*.<
;;:;,- :.
.:,!+
.'.:
- . . . . . . . . 't...d
. . . . . '> .:. <
:.:.
to
perform
quen,es;and
also>con~ol
the flow of the query .....
;..>:.
:,., *: :it!.
:~~~~..~x:<..:,..y:
......
....
.
.. executiol,. ...???%%
. . . ... '
... ... . ..
. . . . . . . . . :*.
....
.: : . . . . . . .
.......
.........?,...
. . . . . .. .. ., . .:. . . '. .
. . . :.
i.

J .

...

A,i.. .:

...

). :.

.-

!.:7j
,:.

:...

r..-5
.. ,

...

,i,

.-

a
r.z..'

x.!

.T,.~*
qy:.,

.:F!>;

.<: ,>:.,;.

,l.-.'L.

......

....

I.....
2..

r.

.
...
.

Y.,

.....
,

-.

.<.

$;

.<'L1-

".;

...
..........
,

...g.*!)L-$,
.........
3

....

..",
+.a:.
.;f--Y.

..*
,.?;.A

,,

,?:??>

...

-,
...........
; . *:..$.
i.

..

., -:

I.*.P ,<

.t*<g,.,2

k..

.?

*+$;.:+:
,29) what
e-..+:.;: '.i
.?&. .
......
.
:> *.

. . . . . . .,

. ---..*.>.

is SesSionFaetor-y?

. :. .
:7..;.z:*.
<.;;,.
..

.....

,;?

.; . : ; : ,:. :,
+, . ;: ;.

:;. ?i;,.
; .

;i'

..:

'.w :j . :::
A . 12.
. :..<
,.: .: 1: .
C

'

. . .... .. ..: . .

i..

. ::

.?h:
:$&:
c
'
4..

. . ,. .

i .

. . . . . . . . .
. . ,. . ,;?.< ;,;.-.

. .

-:. . . .. ,.
2..

....

-;,

'(T'.

.
. .:.
. ,.
,

....

:$~i??$i.on~actor~
.is a$ interface from which the applicati gefbSession
~nstandes
5v.,3!
%a+session~aciorycaches generate SQL statements &d;other
mappMg%netada$a
.-.: .+.+x,;..,
that hibernate uses at runtime. Typically one:.&tance
.
of
Sessioi@&dory at.startup is created for the whole. application. . . .
n.G.x>

-....-.
... .
..

.%...t'.<:<.:...

. . . .

1.

.
.

... :,...

30) How d o you create a ~......$k:;:.&........


i ~ n, ~ a c t o r y ?
...

...

.. <.
.

:j

...

'.,

. ,..

. -",.
....
.!.., ..
i. . :
i
. i

.<!

.!v

.....
.v ....... ,.
s':.*:!,..;!,2.>

.. ... -..
.

...
.
..

..
I
-==
I ~ o n f i ~ ution
r a cfg = new Confrgu$atiov();
I =...&..

-.:

...?.

. .. . ...
..

, ,

1 . 1 .

.>At,

~ ~ b ..::
r i f i .:.g: ~
......
h ,-~ r nll)f
: . ,'.'
~rnl
1 cfg.add~esource("rnyij-stance/~
I cfg.setPropertics( ~ y s t k r n . ~ e t ~ r o p e r t 1;.
i e s:.~.!:.'j
- :. . .
1
j SessionFaetory sessions~=~fg.buildSessionFactory0;
. .....
...;. ;!:. c.,

..

.!,

..

.,

.<..+

--

........

1I

First, we need to create an instanceof


:.. . , Configuration and use that instance to
refer to the location of the configu~~&onifile~"14fter
%$
!.,
configuring this instance
the method
is used to create the SessionFactory 13&%lling
,.,.C*$$
F,=*>p
buildSessionFactory().
...
..>,
.!:p;.:
L~yjTppi.:t ;

r......
.f

31) Is SessionFactoi-y a thread safe object?


...

-.

Lara Technologies

Yes, SessionFactory is a threadsafe, so many threads can request for session


and immutable cache of compiled mappings for a single database.
> '. . ..
.. <

. ..:,,; : . ,

32) What is session?

.......
.. ,. .>. . ;

..

. ...
..:

. . . ,. . .
,
. . .. .

>,

. .

.
.. . . . .

.....

'

--i.

.*.:

Session is a lightweight and .ndithiead


. .;id
safe obtiet that represents a singleunit-of-work with the datgb~id;s;s&bns are openid by SessionFactory and
.....
a persistence manager
closed when all the work i$co~plete..:l~.represents
that manages operations'likestoring ah4 retrieving
. .....
objects from database.
Instances of sessions ,are inexpensive
..*
to d r e, .a<:, t f...f ~destroy.
d
"
. ., ....
.;..;.. tt.;j.: ,
.
........
.
,y;..i;;:,
'2:
.
.:, ..; . ,:. .:.r;....*..*..:
..&.$$ ,'.
A single-the&d$df?SFdfiF1.ived
..
...
object representmg<gqpn~ersationbetween
'?. C . * r.
.-.',. rs, .;
;: ....
,g.<:..:
....... , ...::. . ..
the application
and
the
$%istent
store.
:.: . _
......
.
?.

.(

% "'.

!! ,..

'

.
i'

:.
:
. :..

,;

..

..

:.,. ;\ .,& 3

33) What role-+does


. ....
the Session interface play in HiFi'erii5te?
15 ;
.
?.

;.;.....

. ... .. .
.

j 6, ..?+

.<.. . .;<,> .!
.$, $5 ><;

9.

The Session intenace


.:..F-+:?:.., is the primary interface used by ~ j b e r n a f e & ~
-. .'bg?5!aaa,
:applications. It is~&@ri&?e-threaded,
short-lived object represe&wa%
:,..
<t:.;
:*-$%:2w.
e::h,; ..x>
;
:&nversa~ionbetween$:tIi@a.,$pGeation
and
the
persistent
store.
It
a
l l ,~ e u
:..>.,
..
........
r:;:;
.;,.<s:,;:..
.....
.
.$ f.'.??.
:.
:
.,qzy*:*s/;
..r..
-2.:;:*.:. *..
to~crkate$ier. .:. .:~
objects
.tc+$em.e*e
. .
,. . . . pers~stent
. . .
~.. obj6ects.
......:
;'
,
.
..
. : *. . . _ .
..
.;
.

..

L.;:'.;,;,.;.;?+

'

.; :
.!,. >

<;

c.

-.

.. .. i. .

...

. .%.

:.

(
;

....

;...?.s?.

?:,:,,-

.,

..
. .. . .. . ..

,:?

. .

c.;
............ !.;+*:

'

!.:+
. .,.. .

;.

+::
<:
... .2,:<; .; .. p;;,;+. .>.. :. '2
*, :.:.<:
,*. .
,

.,

.<*.

h' ;..a

.
. . .
.
, . ;.:

.-

<

.,

.:*,

.:..<;..,
...
*.$S

.5

-:
i
;.
..I
SC'J"
....

.. , .*

.;:.

.. .:
. .... ..
. .
.. .
:. . . . .,. .. ,,
. .:.,.
. . . . ..., .
,. .
.....
.<
,....
<
.
,..?

.
i . .

-.

&,\

<,.

....
Wraps a JDB"@connection
...< c.:! ;
+-, ,.:.ap
.
5. ..
$::.
F < :. ,.>~ forT$ansaction
&
~
~
;.'
,2; ;.:;
H0f&i$
.
. :mandatoq-(first-level)
..
cache of pqsistent
objects'afed
when
..
z..:j?{a.":
:.
+:
.:?:,#!:
navi&j*giae
bbj$k@*aRh
or looking up *Gfects by identlfi@
'-. +.'

~~.

;.,?'

.,*

T,;

,<

.-

.. .
:;@ :.
.k

..

$,;

,<..<-.,

:I ; . .

F
::;'

; :,y,

. ....>, ..'

.,:-.

. ..... , '.> . .$! 2 .:-.:..

.,

:... ::,.. > ~ interfa'defrqle:


b ~ ~ ,i -*-I-,~ ~
.

.,

? . . , )
;{
....

:..:. '.i
.::..:;~ b7>:$.
,..=

;...

.:
;.. ;.:
+,,.?..'%

.?.$

:&. ;+,<,

.:,i:?

.. :

2.'.

t p ; y .>.

= se s s l o n ~ b ' &. ..~


.....;<.
olsy
!.. ~
. . . :~
. p .sei q
oS
n e( )s ;
Session'. ;s:e
* . . s!s,j.on
. ..
.......>,:,
*.
. :,.
:...
.< . .... .. . .. .?.

-.

*$?
.&:;

,.?..:;:

>
.

>

,,

1.

i ..;...

.:

._.

;,
......
,.
'a.
+.
. ... P'.
I.3,
...
t .
..: . . .

. ;.: .

,..;
:

.?.

. ,.:

d!.:

. .: ,..:!. . . ..

, :

.. fi'.,

: . .

;g

.>a

!:

, a ......

. .d. . . . .;;; .:
..... . . . . '):;.
.
.
,.. .;. . . . : I.*.
,:
;. : :: <. ,,:.-

. .. ..

,,

. . .

34) What role d o e ~ ' ~ t h & e ~ ~ i o n ~ a c... t b r ~ play


~~n~
ih4-Xibernate?
&rfa~~e
:: ' , .
:. .
.
,::>.
:
,
'!
...
. . . . . .::.;,*.;:!
..
The application obtains S"&$$on,instances
d
fiom&<~$$sion~actory.
There is
typically a single SessionFa~to@kr
... . . . the whole appIiiation--created during
application initialization. The Sess.ionFactory caches generate SQL
statements and other mapping rnetadata that Hibernate uses at runtime. It
also holds cached data that has been read:in
. .
one unit of work and may be
reused in a hture unit of work
...

..i

e.

.-.

;' : ,

...

. ..
.

i.

.,

'

-. .

.I.

.'

.-

>

,. "

.-.~

.!

....

....
....

:.

..
,

Lara Technologies

SessionFactory sessionFactory =
con,figuration.buildSessionFactory();

35) What is configul-ation interface in hibernate?


The application uses the~ofifi~uratio~interface
to specify the location of
sp&cifi,cproperties
and then creates a
,..,
mapping documents andhikrnate
::<,:.
... . . .::
. ..
.....
SessionFactory out of it. ..,;?: ....
. . . .
*.-.

,. .:. ?
..

.:-.

3 6 ) What i S tllegener-a! flow of Hibernate comm~~nication


.
with
. . . .
RDBMS??
..
.

. .

.....

I!:

The general flow of Hibe~xatecommunication


with RDBhjSis
...
:
....
.
.;......
,~>>. ,
.. _I.:,.:., ,...
,
./ . ..s:

..:".
..,>

..,:2.';.
.,. < .<d~.?
,-B..
p.::;l?z ..":...
,

Load the Hibernate configuration file and create configif$atlon


..: <::. object.
. .; .: .
."..I:..~,.'
.!+s.j:v
.
. ;. .
.:
,, ....
.?w.:.. It will automatically load all hbrn mapping files
.
.- . , . & . .
. : : ::;:;;$:$:;Create
...::. .......
sessionfakid~~&omc,onfiguration
object
. . . ..:, . . .
.
. . .
.....
.....
....
*.:
,. ::, .:?. :.
.;;5<:eeti,one
sessioll
jj-0m;;;ih.i~
,~essi,on:$actory
--.
...
... ..... : . . . .
<..!>X7..
::;
. . y<".<:,. .. +
:.;
.......:..
.. ,:,
;..
..&r;..
s.+;:.,.. .. :::>:r;2:%.,.;
c;,<!.
L:.
k,..
:f.':
....
<
;
:
.
.......
"'.
.
_
HQL
d

:.

.: ,

;
; ;:

,...
..

'

. .:. ..
.: . .; .. .. .
:: 'i .;'.
. . ,.. . ...
,..
.

:.
.

, .:..
.. .

. .c<e.t.e.

A.

r:.:,l-'."

......
C:

2.

. ,..
. I

. .
..

>'

.
.
'
d
*
.
.

'-:.

, ,. ..
. . .. .... ... ...

.:;.

..:.

..

.... .

:<

' :Execute
...

,. .
.. :,.

Java objedts:.

to, get list


.

y:,

.,. y?.:;

,t 2

T$@k.>'.::
;:
<+
;,$
:>
-.:,
,.>>..
:$*:&-.
c;.:

&'{'?;.
:.,
..

.....

. . %

3 . 7 $ ~ o wcan Hibernate be configured to access an instancevariable


.....
...
..... .
directly,.and
.
,
not,
through
a
setter
method
?
.. .......
,..>.
.lL:%

.!:. .
:-.

*..

2,
..

. .
....--.:;.

... :, . .:
....

,...

::;-.:Jy7.

B~ &@ping the property with access="field in Hibernate rnit$;data. This


to bypa$s.the
....:ay..e
setter method and access the in&ce
forzes hibernate
._._.
..
..*. ;:*.:
variable directly while:-i~i&alizing
a
newly
load&dkbject
r$:-3f
*
+<<
:>
.;,:
. . ,,..:>, ....
.
>? .; ..
............
<+-,.;:'.
..
. . .:. .. -. ,:: ..::,+ _.
.
.-=,. . ..,fl*&.r;.ji,
,

':-

....

.!,<..-.!

..
.

:.

...... ~i%<~.".:,t,'<:;

.' ..;.. .
. ' .-";
> .
',.>.

,.-,.,h..

<
:.,:

. . . ? .?
..:, .

38) What is transa&tionalwrite-befiinv


.i..i.,.
..,.
. . *:..*. ...
,.
..,.
'...;; . . . . . !.

. . . . . . .: "

..!..r

:_

.:.:
. . .

<.

...

-.

t.

?.<

s..

. . . >;>.. : . . . . . . .

. -. . ..

Hibernate uses a sophisticated


.. ...:.;
algorithmi'to:determine an efficient
. ;.:.. . . . foreign key constraint violstions but is still
ordering that avoids data68se
,,,.
sufficie~tlypl-edictable to the
., user.
.,...
This feature is called transactional
.
.:,...... .........
... .
write-behind.
:.:::.:',
,*ti

.
... .

..

-!

.
--..::.,...[...... . . . . . . .
:':'. . . . .

,",

:.:

'

..

<.;".,ir.

....

..,a

.... . . . .

?
:.:

39) How can a wholi. class be rnap$;e'@as


.
immutable?
. .
....
... .:.;
'.!
..,

.:

Lara Technologies

. .

5;

,:'

,
.
:

:?

L:;...... .:. ., . . . -.,<:s,;:.


..::,&-?
,t
.. . .. .. . .i.;..:... .*:
..... ...... .. .
. . .. .

:,.
. ., .

.-..

:;?.~.:+s;~,>,
:'"><.
;. .

. . . . . ;'>

.,. . . . . . . . . : . , -. :. ;* .
. :::+. :; >?.
....,,,(,
;
;
,:.?<
.. :,..; .. <. k:?:.:

..il.

.":t!e;::

.. .

;...:$'..':1_
.
. .:*..7:.::.,.>.,
. . .

!
:
.

'

::

-: ...

<

. . - ......
-:-_',:.%$,..

Y..'.

. . . .. .

.>:,.

<s

*;:<{,

':

sL!

p:y;.;

,
.:
.:
.:' .

. .. . .. .
..-..:

Mark the class as mutable="false" (Default is true),. This specifies that


instances of the class are (not) mutable. Immutable classes, may not be
updated or deleted by the application.$
1

...
*

..

.?$..:

::

'&;

....

..

. ..
.. :

...
..

....

. .

>; . .A

.
..
.;
.>...,
;:;.:...
:$
::,;:-.,.:,! .?$.$:;.:.?;,,>
,
: .; y...: , .:';.?:$
.. - .:.
... . .:
. ... >
.,,:, ,
,,,.:.
:
: .'
. . * . :..!.>:
. . .
. !. .,,.., ? . - : : . . : ... .,:z<,.x,
> s,. :..\ 1: ;: :. i..;:.
,
..L:
/

.:
. . '.. .

;...

.......

.'I
. . . . .

+.; ...:.*
~$;
- .72.
;,.:- ...:
z;,., 1sr...
; . ;. .,
.

.:I---

.,:

,: ,t;

;@ig,;.,;
:3 ;..:;

--~~:-.:.*.~:$.~:>$.&,~;~.~
$;:;
$..,.;:$x:;.,>\
::;
': 3 <
. . > - .....
..A

:?.

:.

;?:-.: .

:+

...

'-

*.:i
.2>::.
-. .: '.,<
<.:;+..;:.;
,

>
.

<.:

..-:. ', . .

Transisfit .Qbjects are the objects or iiihcesofpGrsistent


,
.;;';:.
.
..
;*, :
;
;.
,..: ..,, not c u r r e az..>.-p in sessi~n.
:-;. :thatare
-..>. . < :
.>
. . . .:

.>

transient object, and persisted@.dJijk~t?

._

Transient;Objects:
. . .2

., :-k

..,.
. .;

. . . .

: 1 4 l. >. . $. .< . ~ hare


a t detaehed,&fekts
... . . .

classes

. .. . . .

'.,.?;:.,.:.., .

.-.
.

,:

!,

....., ,.

.;->.
.. .. .. .. .
1.

.
.. ... . .

.: ....
I

....

:-..:>s..

::
>. ,

.:.:.>

. '

...

.. ...-.
.!I..

.... ..
1,.

. ..-...
.,<;:. .;pe
>.

&tiched ~ b - ~ ~:. t. . ~ : , ,
. .. .

;.'.:$!.%,

....'
'

3..
?

.?It

: 4 ::

,..ah*,

gy.:! .;,

>:.

;:>.;:

~ : & t a c h e dobject is an objectthat h i i b e e n persisteni 'out;Xhe-session


is closed bb$:.&ll.An be
to hnothq sessibn. and those obj$.$;ts
52 .$c,
Can be
passed across lay&s all th&w&j~
. up,t,o
.
the ljresentation>ayer,with@? having
.. .: : - .,. :,, ;$+'
. ._ :..,
. ..,. .. ..;:.+..;
.
to use any Data Ti&fer Obj&ts: 3 :l..
. . .

. .

..-

( / . :

-';

:J ;

-.,:$:

:,.

'

. . . ..,

,: !,-:

D41i2

Pros: Can b e passed. up to presentation~lay~.l.wit:hout


use of DTO's
!,!..,', :.; . . . . .
.

. .. . . . .
...

.r

<'

.-.

These detached objbctsget modified outside &,:transactionand later on


re attached to a new transacti6n't3.do,;ugh
.....
another session.
.: . .
.:'.

Cons: Working with detached objects is quite cumbersome and using Data
Transfer Object for the presentation layers
is better than using detached

Lara Technoiogies

Persistent Object:
Persistent Objcct is the ~bject:~thiit
. . . .,. isin session currently. It has a
representation in the database and.&k.i$6htifier
.;.. .;.
.:. ...
value and might have been
...'. :.
,>+&$@$Y
...
saved or loaded.
.;, ;! .S.;~?)
* %..,
..
.

.:

.,

,,it,,:
>:.:

. .pi

. . .

.:.

.,l.

'

<./-

.'.<&,

,: ,.,2.<:-

2xg5;.
.?~:,.-.C~P:~~~
l.; ...,...';.r'.
;+aa.z
;,
cx
,>.;,;.~3..:j.,;

42) How does ~ibernated$stfiig$i$&~~between


. . .... ..,,
transient and detached
>.:
...
.... ....
,.
,.!:.!
objects?
...
. . . .....
.
. .. . .
.XI.

- . + . . . ,T
! : ;::.j,.+.
j~~.

...

,?,<,

>.., ,.:

.<..:.

.
.....

,.

.'.

......
: . . . ::...

'.,:.. .

;.

.-.

..

,;: .

'C,

.......

i_ ,

'. qj,

. !,

<

: ."F

:-:.

-.

I,.

''

.-

.?

5.-!.

uses identifier

or

Hibernate uses the version $igPerty


if th&&&ist
one
..,. :
. . ...
:
;-'I
,.
value.
:....:.. . .
. r:.: . -... .
+...+.-.
--.
...........
': . ;;..

*iii.l

Sk

.,?
';

.?

'

43) How do you switch:b&veen


>.:,:.
relational datib.k~eg~itlluut
code
..
....,. ...
changes?
"..
..
...
. . . . . .. . . . >.'...
.

<#.

....

_I.

....

.;!%

.-,. ..
..
:., .
i.

,.

?
.'.

. , , .. ,.. :.<
,.: ' . . \ - c

:..

!,

::y

;:&

Using Hibernate SQL Dialects ,we can switch databases:'Bl$emate


.,.*.:-:.
,.=
will
generate appropriate hql queries based on the dialect define&$$:&$,
. .
......

..

,.

%.=. :.

.
...
. . ..>
. . ... . .

. . T.

.:; .? r

&; ......
5
,>
-.. .....
.
<..
.
.
.

i.

;.,

....

,..

...
.

<'.

.li.T<.
.'

2%:

.....
J..

..<

y;; ;
:
::

..

...;'.:x,.

.
. .
.
::ti..

'"""

'C

'"&BG2>&&&E&%:;

3
:
,
c

........:
. ." <$-e>
c*
.,+ - 3".: .k..-<&< -;..,,?;

!:;

.$.is

;.

-.

.,,..
;.:-; .
. . ::.>,21;$,.$,
. .,..:>
..', ,,:?:.

<,

:.

..,

..<*..$+:;..,
... 2...:,
.:<<;,::.-p::>.'..
,:.*,
. :. .:\

...:.
.>< .. <.:.:,;
....
. .:
.. .. ... .. ...l .
. . .~~
. .........
..
:-

i-

'T

'.>,.. :?'.+
*:.:.:.

,'

.. .. .

'.

. .. .. ..

.
.
.
T

'?.

..?.,

<.

;..;.:.

: :>

?..:;<:.

45) H6Wdo.
%+;:: you. define
sequence generatc%;primary
key in @%&ate?
. . . .
,:.
,

. .?
-4:.

<:.
,
.

*;

....

i$;@s><

.:
..,

i::
<.,.:

Fz.y.y:d..::.';
..\.,. ,..,;
.

.:>.,

. . .. .. . ,,.

.>.

"

?.>,,-

... ,

. .

<, so.

%&&i
$i:*;

., .=,<<.
;-

:. ,.:; ,>. ,.+::g;


... . ., .
.--.**,
;.!... .,,
h .,$
i !.:!.
+!!
:
.?.,.+:%
,,.
$...:
.
. .. . . ..
. :
.

.
I

,;

v
L;; .

,/

.>.

<id column="US.ER-ID" name="id "iyp~=njava..lang.~oig~~~


.... ,..... ,+;.
s yf .t:,,.';:
s ... ;. :. ..:+y: .:.,
.;
.:.... ;
. .. <!,:; . !i';
<generator c!ass="sequen'~e,">
.+ :
,%?,
<par;l,lm nam e=".;abie " > S ) e Q j j ~ c E
Q>;,*g""
:,:
.:.
<generarot-;.
-.+.,.- ..*,..::
Av.c+.
Zr'
.?,
....
<,!j d>
..e::c.?,
. ... :k.,,:
.-.
.....<:;.:
.+ ,

1 ..?:,.,

j,,.?

-:

.v r

?';

.:.. >. .>.,. ". ... .. .. . .. .. ..


........

46) What is HQL?

...,

......<

LC;.

-., :..
. ..: .>,

..

Lars Technologies

.;

.x +
G
,+
;&.:

::>.:...::9 :, ...:.,..
7 ,! ::

, :..

.......: ; :..

- .

'

.<*.A

Using <generat&> tag. " - ;+$$&,:,


??%&.??.
.;:
Example:<:.F.::.
.FP~<.;:., :.r.,.r..,
.
.

..&:
4$.?2

.-;
-? ..i.
>.,.

:,: + . i

'

....-,

- --..-.
. .,
-*2.:->
......
-*
...f ..'..,.'S .. ":

... .. .,. ..

. .

y:!;=.*r.
......-.
:.. ....
i
;

,,,,,

. .

:.<,

-,

.*;.;i...A'*
.,"
,

,%

:;:,..v?.::L

7 : ;

., ,

Z?
p.:

L$.*+$rz&

..

%.I

:.::..
. ....t:..,
s i '.i2ih~..\'

...
~:~,.~.:~~@~:+<L
>@g;z:.
... :I. In Hibedhie configuration file s e t . ~ i f ~ ~ $-.....w4
...:
EM" ::;::>%,:$$P
.*:x.~ . .. . y:.. .
. . .:..
i:.::
:<propertv name="show-s q l l l > t r u e < ~ ~ ;.::,.r ~ p e ~ $ ~ + y >
. .
:..

?,!

i'

>

..

....
waiit to see tkeii~ibernate
.... ;::: .44)'H;3.0u
>.,:$p$v+G w. .......generated SQL statemeoth?o&'::,
. - ..,..
..<.!G
:.,
. .<
. . <09&GyT
* .,.".'.\"
:yk.;:rz,y>,:v$... .;:.'Qq$$?;;i
.;
.
.
...?..
consoi,e,,~wb
.
...a t shou Id we d:~~44~i:~i$~+~:B~g.TG:~
: ~;,
2
,
.,.... .".
:.:.: ..
., . ,;.,;,* ;+.&..:p'"-k
;j$."
.$ ?:;,

;e >:;,

.-

.:;,i..

. . . .'I
i r .-.
.-:* .;+;
'<, ..; >.
?.<:.,

:
; "?.;?:"'

.,

~-.:

HQL stands for Hibernate Query ~ a n ~ u a gHibernate


e.
allows the user to
express queries in its own portable SQL extension and this is called as
HQL. It also allows the user to express in native SQL.
Answer 2 :
Hibernate offers a query language that embodies a very powerful and
flexible mechanism to query, store, update, and retrieve objects fiom a
data base. This language, the Hi bemate query Language (HQL), is an
object-oriented-extensionto SQL.

HQL provides-four ways of expressing (inner and outer) joins:.. .


?.
.

. .
,

.:.

.
. .
.

.>

..
...,... .. ... . .....?
. .. ,.

An implici~associationjoin
-Ax ~rdinaryj'oin~in
the FROM clause
A fetch join in the FROM clause.

.
..

.. .,;"

. .>'
,. .,+. +.,
!...:.

. . . .+
:. : . .- .. , .
. . .

. . . .. .

.,

A theta-&&
..
join in the m R .E clause..
"
. .
.
48) ~ x ~ l a i & r ~ r i . t eAPI
rja
. . .

.:$

<.

:.

....

.. . .
.; . ;.
;:..

......

..: >$.<..

. .
.

:,:

.?

. .. . .

;.

:..
,i

( ..

,. ..

'z

; ..

., :
t .
:.

.
.

:..

. .
. , . .. .

. ; I

,.

-: e.Gr$eria is a simpj$fifiedAPI for retrieving entities by cbni@osjngCriterion


.(

$e&

...

?.

This is a .... convenient approach for functionaIity.like "search"


.objects.
....
scrbens where
...
t h e i S.3. ~3. variable number of conditions to be plaae,d
upon the
,:,,:..."
:.: ..+
result set.&:,,,
,*.,
7
y:
? ..
......
.', ..,:'. .
<;!j::.;
.: ;:
. ,.. ..
..._
.
EXampICti??:$-:',
.... ,.
...
......
:...
(

%.

*,

'. I

I.,.';

.:.

. . /. . .
..,,.
,.+. . ?

>

. .?>

,b?

+..

.?
.

,.%

. :.
:,,:

c.

. : . . . . . . . . : ..: .;

._..
. . . . .

.i.-

.,;.

..
.

:,. .
..

.. :.. ...

..

..:
c

.
.:

List empIbyek+. . session.cre~te~riteria(~m~lo~e~~class)-.add(Restrictions.like("name", "a%".))'


.add(Restri~tions.~~.ike("address~,
"Boston"))
. a. ., d d ~ r d e r ( ~ r d e r . a s t $ ' n a ~ ) )
. . . . .. .. : .
:, . :
.Ii si();
49) What do you mean by h m e d - SQL cpely? '
.

:.

'

'

./.

::.,

Named SQL queries are defined in the mapping xrnl document and called
wherever required.
Example:

Lara Technologies

. . ..

Invoke Named Query :


List people = session.getNamedQuery("empdetai1~")
.setString("TomBradym,name)'
.setMaxResults(SO)

. ..

....

;
.

:.:::;50)
How do you invoice Stored
Procedures?
.
......
.....".
.

.
.

".
;.

" : .

. .
.

., .:..:i_.:.
< . .. ..

. . . . -.. ., .
. .. ,

<. .,.7, :

.;..

I- 'T
.: ,.41,
. . >::, ,.
-7:.

.' .

-1

'1..

'

. .

<return-property name="namell column="EMP


.
-NAME")>
< $ ~ ~ m - p l - o j , e a i y nsme=lladdressl cojumn="EMP ADD&S"D
: (:;..:'r
*
+:
* .-:.
::,.
2i?=
. ,.:.
call seleciAIIEmployees() }
. .......
,..
..
</ret~in,>
..
.....
:,

:.,I

..

.
.

............
;>...,
:.

51) What are the types of ~ibernateihstancestates ?


i

. . :. .. .

, .,

Three types of instar~cestates!.


.

>
.:.

'..

Transient -The ii~stance'is.not.associated


.,.
with any persistence context
.. :.,...
a persistence context
Persistent -The instance is as$okiated.vith
:..:
.

;.

...
,........
.:..>;....
, . .:,
,.;:
.,.;>.

:".:

:. . . .

. . . -:

_.*l,

Detached -The instance was assodiat'ed with a persistence context which


has been closed - cuuerltly not a$jhciated

Lara Technologies

080-41310123

52) What's the difference between load() and get()?


!oad() vs. get() :-

Only use the l o a d ( ) metho:d if you


are sure that the object exist;.
'

''

:Ifyou are not sure that the object


then use one of the g e t ( )
. i:%x.ists,
...
<
:methods.
.5 .
.
<..* <.,,

<:

':

> .*.

.:

. . . .. . .

1oad ( ) method will.throw an


exception if the unique id-isnot found
in the database.

..

get'():'method
will return null if
...
the uni;luk:id
.. . . is not found in the
database.
7

.
1oad ( ) just returns a proxy by default
g e t ( ) will hit theidatabase
:;..
. ..-.
and da&b2se y:25': behit .il~tilthz
..
,
immediately.
. . . .e:... .?,.
proxy is first invoked.
b.5
...........
.
. .
.

1. .
: -...
,:;?. .*s~.:.
.
i

A:.:::.,

..?.+.

: .
1:.
..
.-:.,:. . . .... .,.

. . . .

.. . ,.

. . . . .

. . 3 .1:

5 ..,;

.!?

,<.~
.

'

''

.,..- . i>;."

.
:7:
.<<. .
$ :.. ,
. .-

::

....
.
::-:
4 :*.
..
53) ' m a t i s the diff&ed6&:bktrv<;,band
...
. . . merge
. . . . .,.
and update ?
.....,: 2. g.;.
Use u p d a t e ( ) if you are)&$e that::the:&&kibn
does not contain an aha*.
.. . . . .. . . .
'
'..
persistent instance
...
with the same iddntifi&i+qjd
:> : . . . m&$e
. . . .
( ) if you want to - ;:: j
',.
...
merge your modifications
..~.
.
at any time withdut c o e i i d-. e i a t b,. ~of the state of ;:,. .. . ,. :. .. : i
......
6 i?,
;'
,-:. 7.:; . ..the
session
. ..: .
,, .. ..;.k
... ...:.
.... ,_
<.
:. . .:, ..
,.. .. ..__
>>
:
. . . .. .
.,,.
......
. .
. . :
....
. ...
. -..,.. . .:
:,,

"

, :5.
.rx..

,L

>

..

;..

.&

.......

'

. . . . .>

'

. .

-.

.
*
i
. .

ii*

54) What are thecbllection types inHibernate ?

..i

.,$,a

...

. . ...:... ...
. . .
... . .
.?

Bag

<.

Map
55) What are managed aSsociations and hibernate associations?

Associations that are related to container management persistence are called


managed associations. These are bi-directional associations. Coming to
hibernate associations, these are unidirectional.
56) Define cascade and inverse opiion In one-many mapping?

Lara Technologies

080-41310124

.. '-..!<:.., ....'>
:
. :.
;..
.. : .;:, z :

.L

'.'

!.

Cascade - enable operation.to cascade to child entities.


Cascacie = "all I none I save-update / delete I all-delete-orphan"
.

.l

Inverse - mark this coll e c t i.0..i . i th&?inversen


~ <->
end of a bidirectional
.
.
. . .
association.
....
.
.

. . . . ..:
:
.,.

.-

<:

..I

Inverse='..true(false"

. . .

.... - ......:'.
..

~.

.. .<... ....
,

...

..,, ., ....

.
.-

.
. . . . . ..

Essentially "inverse" indicates which end of a:$lati.onship should be


who hiis coll&~on.of children, should
ignored, so .%hen penisting.a
you ask the parent for its listof children or ask the children who the parents
are?
:.
:::..
. . .., . . .

.-

-.

'

..,;

,:::.

i..
.. ,:>,
;

'
.
'
k
'

,;:;::q-<.,
.+<:>A:G&~,%=

57) What is theuSe of dynamic-insert and dynamic-updgt@$+%ibutes


-9: 6 ~ ~ :
in
-x$+:t;,-..,L
.-i-~~a.c~ass
.
mapping?
,+;a$7?
'?31:::;g>
.....:..,
-. .,.?<......
.,.$$;';rpj&
Y& g >: .p!$.$-"Ti
,2:.~;~<3:,;>~.;::3;~:.,:
,-

;. Cr1tepaasi.a silnpii fi ed ~i

<,.j<,
:
0

...%,.

:
i:

"

.....
;<+:
...

.:

.......

C . . , ; p .._>

. . .

:.,............
=::. y:.Ls;.:.

.; ..:g..::
.: .::

fir;reui&ng.
entities
by composing Cnte@?$;;.
...c:. ...........
s,:.<
.<:::;;
:..:,:;
. . . .
.
.:. . . .
* ..
objec&;nis, is a very convenient
.
. ..~
. . .~
. ..=. p
....
. .~
. .,.
. .o
_. ..!for
a. . .c. . h.-functionality
....
like isear&$<.;
... ..;
,.!-.:,..i-~,.
r.
..-.,
,Gscreens
$&re
there
is
a
variable
n~fi~e$~p$~on&tions.Jo
be
placed
upon
ae:~c;;:
,?{:,;!;,~
' ~*,
...:
. . .
.:?<!;:;.
2 . 2;-:i%,x
$:<:?.:
- ,.:: :..! ., .
.-.:
<F
-'.; ....... *....
. 3:q &:>
."><
... ,.. . .
. .:.
...........
..
.,
... .- - .
$....z<y.
:,result
set.
,
: L<<i.< >!:.g ..
.<<"...
. .. .. . . . . . .

.I

s.">,

,:
'.?.-:".I'.
- . '.........
- I ;
. . . . . .->
. .......".!.........
<..."

P.. ,-.,.

- .:

:
,

.....

,.:>

.,

<
. . ,. :>

, . .

,.

*r..+.

-..<

;..+

6-.>i.

<k ., 3>,*.-.
,

<!

,,,

..i.

v , < - . .

%.,<.

>.<....c

,-

..3

<

?<

;"
:
;:-, ,?rr&.
.*
:
;

-.7. . . .!:.?

.*;,%:,.?:$%*

:\

. . ., . ...
.

dynamic-update (defaults to false): S p e c i f i e s : t h & ~ . u


.........

.........y?..y!.ycy+?
?
.,*:

::. , . ., ., - ..
:

.,.*k..

C $.:.-!..7.
.<...I.,'.*
:

D,

. . . . . .
.............
>.,<<
, ..: $ 4..

$+*r.pt,

'1.
.4:;?\",
.
*"d. f .

i r.:..r1..
, x.

:.:.

.. . ..~.
.
. . .

&id$'

'

~I:;'
~~

-$::!.!.3QL
.
should be generated at runtime and contain only
columns
'kwKosevalues have. changed
.:.,.'.
d y n a r n i & i n s e r t ( d e f a u. l. t.s , ~false):
~
Specifie~thztINSEF&&QL
.:-.
:;
:
.@
.
should be generated at runt~me&d:contain
.
only the '~:@~urn?.~~~y&~$@values
., . ~. ..,
....*::<,,... ;-;,z+i*+.
!: .: ,. ,. ..->,: .,...
.
are not null.
++:.:: ..?m+;i.::>.
,.

>..

._:)

..:.d.?.
?
,

?::. p.

..
.

;i.

*.<: ;:,'.'.

.!?. . .

. ,.

L...?

<.,.,Z
:

;.

r.,<. ,:

7 .

..: . ,

*;:.

...

. . : . .""~m':;.i.::..

::x:c :::>,;.;.:;\,. :I... :,i:?

-,;:.?.;p

:'

58) What are derived properties?

.. :, y ,.>;I; ;,. .;
,
..5...
s!._.:.;...". .i
:. ;j. :.:.
. ..: .:. .
!:.

. -.

v.+
'(
',; :
:

.'.

~'

:*2;.?:,:2
'

. . . .

The properties that are not mapped to a column, but calculated ai m t i m e by


evaluation of 31: expl-esslon are.:called
. . . derived properties. The expression can
be defined using for~nulaattribute o$:the,,,element.
....
. fz
..<?
.-

r,.,:..

'

,-.:..........
..,..,. . -: ..
.,: . :, .:,; .: . .
. . . ."..
. . . . . :.
,,:t
..
..<
.> r.: - .. ;
.,....

!'

r....

:'

59) What is dirty checlcing?

..,.:',,.;
>;

*-;J:'.;..,
.,

,.;...:

Lara Technologies
...

+,

; ;<.

.I

~~

Automatic dirty checking or dirty checking is a feature in hibernate that


saves the effort of explicitly asking Hibernate to update the database when
we modify the state of an object inside a transaction.
60) What do you mean by fetch strategy? .'
...

A fetching strategy is the strategy Hibernate will use for retrieving


associated objects if the:applicationn2&s.
....
rto navigate through the
association. Fetch strategiesmay be de&@.fed,in
....
the O/R mapping metadata,
; ,! ji ;.
or over-ridden by a~particul&
HQL or CntgcCQ~ery.
..... ..
. -.

.-

;*:it.

.:

,..

.:

...
...

>.

....

"..

.. ,.-;:...
"

.! ', .

.,-.... :. . ..
I
. . . .. ... ...

61) What,-Jd~~yo&~&h:by
lazy fetching?
.
. ,. .. . .

>:,>,

,,;

' . .. . , .
.

. ....
....

..

. .,

..

, .,;,,F *

;.

It's a fetchf$2~strate~~
used by Hibernate to constraiiit'the
>.. ..;. retrieval
.of
... ,,:T +,:,
associated dv&cts
_ ,..
when applicat.ionjust needs the objects$&
doesn't need
.. . .. . :.<<.:.
. . .... + .:
to navigate thdT&sociation.
.
,.:.
;;.

.:.

<

. . . .> !::..

,
I

: '1.

?.* .; '.:. ,.

:.;:.,'
r.: :::::,
;.>.- >,:. .':,

. . . . . . .
...

. .
.......
.

...

,. . .. .. .;..
..,..
.... .

: :+;..i62);:What
is ta b l ..~ ~bclass,
~ ~ table
~ ~ per
~ class
s u hierarchy and!ia@le..per
; . :.
.
.
.
....
.:!;.:. .: , .:.
, ..;. >
.........
.... .,,>.
;;.;:.;.
. . . . .
. . .... . . .
:!:r ....:
-t!cong~,ete.
:. . :L-- class
.:.....
. . .
.
"
.
.

>

.
..

.f

..

:.?2,.>,

:.
. ,.
. . . ..
....
. .

<.

.::
.

..

.....
:
:

<

: . . ..

.. :. .. . .
. .
',<
. ... .
.,. ,!
... . ..

~_

a.

.. . . . .

...

Table per sub'%cp: ass:


'.

. .. .. . . . ..
. .:.. . . . ..,:.
..,.. .
. ....: I
..'. .
......
... .
.;.
.z ... ..

. :

bas&$,

. .
. .........
.;". ....

..it

These'& aib.;i.&ritance
. . '

".

*%

c. !

. . .

. :.;

'

.:

;; i

:
:.;.. .;. ..: . ;.. . .. fi ,; . . . . . . . .
*.
. . . .. . . . .. .
. . .
. ; ;
..
.
. . . ?!. .......
;::,:,
;x<,
.
. . . :...

.,><."<>.;

.?!.:

:.... .

..,:,

.$..

..

'

: ..;.
.
. . . . . ... . .
I

...

....
....
..:

-Maay to one
If you retrieve book then publisher is also retrieved with it.
\

If you use getpublisher without closing the session then publisher is


accessible, but if we access publisher after session is closed then its an error.
This feature of Hibernate is called lazy initialization. This avoids
unnecessary database queries and enhances the performance.
64) What is unidirectional and bidirectional mapping?
Lara Technologies

080-31310121

152

..

I
'

--II

<c,:,>pB.y.: n-.n:+=kiw~<';:.

.-...-

..

:...

.:

..
. :. ;..
..::<<..::
.:..
ii
.-.

..:i

'

..

..p~,>p~;;'
l-,.~ir-1;~=-post:3~~;le
'f..
.:~ * ~ , ~ - . ,-,:{-I-:
~ ~ : ;2=.1iit; >
l-,GIlt

: :1::1ty Kt:

:-

. . .

..'-I-.

.. :...
,.,.
.... <.
. ..
,. .

.....

. . . .

. '

-,

*;

..?.

67) w'hat$S?ihe
...
difference b & ~ e e ~.. $. .d ~ t e d .:. :. . a f i d < ~ r collection
d , e r e d in > : ? ? ::
.
. . .
hibernati?'.'
. . . .
.
.
.

. .

%/

,x.
- ;

col1ection:ivs.
. .. order collection :?o:r$ed
<, *
.....
.:+*:.;+<
.......

i.

::I

?.:

.* .:........;..
., >.
...
.,,(,

-.,* .

...*...:..

....

1..

'!.

?
.: ...
...-:.;,.,.-I,'

il>
',:

.
...

c. .:. .

: .. :.

<..

:..:....... . . .
'

. ;<: :.
=: .> *.:
1. :.. ....
.*? ,'
z,

-.

-.,:.-._

.-.

. I:..

..

,:;

.. ?: .
:.

.. . . .
. S,.('

...

.:,

order co1lectiCfp

:sorted cd!ec,tion
. . ,.
....:

..
.....
. . I

..

., . -......Y. ;.:

,:..:..;

. . ....
.

, .

A sorted &$]ection$i
a
collection by :util.&hg: sorting
.:
features provided?hy,
.. . .. .,.the Java
.'. .... ....
collections fiam&ho$k. TIle sorting i
occurs in the.mem&;:$f,~~lviwhichrunning Hi bemate, aft&the data
being read fi-om database using java
comparator.

order colle&$~fi;yissorti,r$a
. .
. .
collection by ipeb$Fj6ngfhe order-by
clause_forsorting this collection when
t e a : . . . -. ;.

If your collection is not large, it will


be more efficient way to sort it.

If your collection is very large, it will


be more efficient way to sort it .

.;

%
%
,..,!'.

IJaraTechnologies

.,,

- ..,

... ,

.; . . .

%
.

,1

., . ... :
:; ;

,;

..;. . .. ..

'

"

. .

.
:

. ... ..

. .. .. . 'L !?
. . . .... .;:c
:.......
:,

:.?:.

..

..: .

If we want to get reference of child table or object while retrieving parent


table or object and not vice-versa, then this type of mapping done is called
unidirectional mapping.
. .. .. .
. .

. .
'..

,.I.:-;.,:..

;*::$- '.>;::"
":., :.
.,2:.

....
;
....

.4

. .::

If we want to get reference of chi'la&ible


.! .::..,:c!~.:. :.
o r bbject while retrieving parent
table or child and also vice-u.ep.q&e
....., .-. ..*.:R:this
-;,
type of mapping done is called
;$;:.:
.;.:
....
bidirectional mapping.
..........
-:gy::
,~~~x:i~..~.!.~
.>+:::
.....
.,.. . . .. :. .. .
,&,:

>-:;x:::$>:

,,

.,c.

..+.:<:.... .,).
.<.

..............
....
........
. . ::..
. .... . '

.....

65) Explain about collection


mapping, association mapping, component
......
..:

i
?
.

mapping, inheritance mapphg?


....

2,

. . . .
.:

..

,..

,,.. . . :...:

It's a kind of mapping done... in Hibernate to m a p a coJlection defined


in persistent java object. ~ a s i c a l l ~ w
can
e use Bag, Set, ~ i s t , : & r a ~and
,
Map in collection mapping as defined in Java Objects. ~ i b e ~ $. .,:.::>t.,, ~
~:. : b a s i c a l l ~
. . .
.,.$:$:a-:;requires
persistent collection-valued
fields be declared as an inteTfaZ4-type.
... zin,y, S'..
*.
..<:..*,
...
.!"d{@<&
.......
: ...,......
.<..
................
.;. ......
.'
.........,...
..;*>,.
*.,
..... ,,
....,,:pr*,f..;.;. -,".r:.. ..
.. .-... . .
........
;;;;;$k;iy;it5+;::
. . . ..'..*.
.. ... .. ... .. . ..
Ass&iation M appinrr:.;$,:;zg;
;~;,:;g~;~;~~<~~j~~;~:
......
?
.?$
,:;>
::
.. <:?$$.;:,?:;:;:
:.s ;f*.;Z'
!.

...

.;

,k.t?
:.:. "
<.
,
....

.
. . . .

'

..

r,

-.i.,

.>.,.?

?
:,.,

.:; 2;.

.:

..*.;.,t

.
;.

:,

i:.;,l.

. I :g$:.:.between persistent
,

. % . .

..
1t's a mapping done in bbernategenexalJy td-Ghowthe relation

....
.;,. 'Cr .
'. .:<a
.
.

...,&?."

,:k:;i ,,
.

>j+s;
.....;El
.,r^...
l:........
:I;. .::I 1 :,
.-.;":.v.
,.:..'+:.s:..
.
. $ ;;, >.+;
- . 2%
.<..~.~~i<:;,~;.~.,;:~'~~i~.;_.~:
.... /:.. ..
.% .,: :.,.~y..<.;>?

,:.

:.

.,&

.1
.? :
; !>i-,z,:

.;->.,

::

5 .;
";y.
..

.... :.:
....

. ,'

i
u.

?*:?.

. ..<.+:.

.......I

;.A

,:

.:t:..

..'.

.
.

c'.-!.
.:.;;:2.:;:;:;

:;.r.,:

,.s

:.

,,:.'s7,;.."

.
.... .:
_:.:i.

... .:. . . . .

. c:..." ...... .
........
.,...
-. --..,.:
:.a<:

.:i;;:;j3:.:i.3
;.>.. ,
. . . .............

object. The different mapping often;-used


:,.. :. !. .. is one-one, one. . 'r;.*,.;-.;., .:..
-\.:.x3- ..+:!+$.
..:..:many,
many-one,
many-many.
":!> :
'5;
. ..
.

.;: [. :.

$
:.:.

.$'.>::<.

<
..

'.

..A

...... .

? ,;:.;

...

..- .y. . 1.
. ...
.< .
.- >
1;.

.-?;:.!

........

Ii's a-mapping done in Hibernate to rkpcomponent


.,..
(cordposition in
OOP) which is later pe~.sisted::as
value *e and hot-entity
type. g $- i
.:-$;s>e;
.
%>.it.=L
,.
.,..
..?$;..Kc:;
q:>..&;&> .:,<:;. ;.y:, ,. ....
.:.
.
. .:.. . < ,:. .+:>s;g
.

.$

:.

.*,!<<?<

.L:

;,?:I.;

.,,.,! : ...'.*c :
.:: ?

1.:.

6 6 ) W h a t i s c o n l p o n e n t m a p ) l n,,,..:;..sg ~ ,:~.. ~...i ~ , ~ b e r n a fx2,"


e$.??. i,,:.;
..
...!
... 3=a,; . , :.

.-.

'

:-

.:,

....

,.;:

.:<;:.

. . . . .

.;,:*.,I;;;
.

:..

?in
?..$.;:;
.;.:$
.;.
>. .
:.

. a Ur

A component is an object saved;"d-szi $.ilue, no.tts:a


. r,.'-i...i
reference
:.

. . .

-4component can be &iK9d directly &thoi&n&ding


.+;.:
to declare
.-, c

interfaces or i~ientifiei$&~erties
g;:
::+ ...&,
Required to define an empty;constructor
.;:.
+".,..:
Sharedreferences~~otsu~~o&e$~
"*.. +
-,.. . ..- ,:,... .
.
::.

;.

,.$.

,2. a

Example:

.* ':

.. ,.? .:,.... ' . : 2'


,<..:;, .
;,: .. . . .' 3
''

'

: !.!

.:!;..
. ..%.

J'?. . . . . . . .

.
I;

. . . . . . .

,; ,. ;;:i..;.
.. .-..;.
.. . .

.. ..>.;,.-. .

68) What is inheritance mapping strategy? (OR) What are the different
approaches to represent an inheritance hierarchy?

It's a typical strategy to map "wholelobject graph" which are related to each
other through inheritance. We use hese inheritance mapping strategies
,:.:;,

.: ..,:
. ,..: .. . . . .
..
';

.:

ableper per
- subclass 3. Table per concrete

1. Table per class hierarchy


cIass

... .

69) What is tnbIe per subclass mapping?


It's an inheritance mapping strategy in which we create table for each
~ ~ b c l a s s*e s...kthe
h inheritancehierarchy and map it-accordingto that in our
.....2,
<>.
mapping metadata.
......
: .

ll

70) What is table per cIass hierarchy?

,a

.
:.. . . . . ..

,g41:2${7.s
an inheritance mapping strategy in which a sing1e table is created.for all
.:..~;gd"s;.:;;.
.:;.. % ..,
,.~,..,~~$@&%%~lasses.in
the inheritante hierarchy
and map it accordingly in our mapping.
.....-...,.
).~~;57g;,:~g<G..?,
s?3;.s2:;*i:+%.

,Q

YE?:::

...
,

......

.,A

...
:>L:;@&.::..
.::;,!&& &5;.:

..:;

%
;:.

...'. .... ..'..; ..,...*-.


.

.:

i . ;:$,!:.
.

.,?
'

,.a
......

,
...

...:i..
...:...
":. . . ..: . .. .
:;. . ..,i:v;::.:
. . . . . .:

. ..

:.....:. .> .:

71) Whz+$'table per

?.

,..
.
: <
...,>. ..,:*:.:
..
: . .;,I .- .;.. 1
.

r;. . . . .
c.;:.2 2. .,.- .
.

fil~~~~;$:;;$~g,i

,..,g
<. .....
-..
,
. . .7.-:_

;:-.I'

:.

. ,
:.
:
... :
,..,
.-.
.... ........:
. .. ~

7.

';,,,?.'.
L

ret&dais?

.i.-

.*.. :....,..; .....


..I
...
....
s:,
.. ... . . .. . . .:

. , .

..... .: . . . .
. . .

. .

..,

. -..:.I.

;yi.

.:.' ,
. .:
.:. .. . .. ..
:. . ...
..
.. . .">
i

-..
:5.
1. .......

inhe~-itance.mappin~
strategy in which we c~.ea_tg
[able k ~ ienih
<,..
ebq$~ete
... +... ..:-.ri
c!s.-::< and.inap it accordingly in our mapping fi1ein:Tava side.
.. , .:
..........
Disadvmtage
.-z.ia::t;-:4+
is that we could repeat the same properties in theconcrete
........
.....
classe'$~$$luding inherited properties.
...

<;.$i.:<,<,
of the
..,.T$$$i,.one
..,: .: -......
..+' ,

.,.

-:.r...,{. , :..

q;:'..::.

'

'. ,

SV. .i:

5 . ..

. ...i...:

_:

..: .. .. ... ,

EJB 3.0 &Hibernate


.
?$..:$.
72) Wha?:~r&the
differencq9::between
..+<.;
<.:;;. .,.. . :
;
... '.. .
,,'<;.?..:
;:,:.!;:.
. . .. ..... .. .. ..,..:
.........
. ..;. .
,:*s:
.:;.............
. . .
. . . ..
.+:: .. . . . .. ..:
Hibernate Vs EJB 3.0 :. . . . .
.
...:

::,.Zs:?.

:-;..-

. :\. .%
.

:.

..>

. . . . .,,:?
.
.: .

J+,:".. .:

>

.% . .

. ;.:

. . . . . .

.: !
$

I
.

......

..!<'I

Persistence Context-Set of entities


Session-Cache or collection &$o.aded
.,.....;...:..:..
+
that can be managed by a given
objects relating to a sillgle unit ofj,.':' :..
.. EntityManager is.defined by a
work
. . . ..
.:-:>: persistence unit
.
.

::.

XDoclet Annotations used to suppoo, Java 5.0 Annotations used to


Attribute Oriented 1'1-ogramming
: support Attribute Oriented

Lara Technologies

080-41310124

...

. ,..-

Vous aimerez peut-être aussi