You are on page 1of 30

1.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.
2.What does ORM consists of ?
An ORM solution consists of the followig four pieces:
AP for performing basic !R"# operations
AP to e$press %ueries refering to classes
&acilities to specif' metadata
Optimi(ation facilities : dirt' chec)ing*la(' associations fetching
3.What are the ORM levels ?
+he ORM levels are:
Pure relational ,stored procedure.-
.ight objects mapping ,J#/!-
Medium object mapping
&ull object Mapping ,composition*inheritance* pol'morphism* persistence b' reachabilit'-
4.What is Hibernate?
0ibernate is a pure Java object1relational mapping ,ORM- and persistence framewor) that allows 'ou to map plain old Java objects to relational database
tables using ,2M.- configuration files.ts purpose is to relieve the developer from a significant amount of relational data persistence1related programming
5.Why do you need ORM tools like hibernate?
+he main advantage of ORM li)e hibernate is that it shields developers from mess' 34.. Apart from this* ORM provides following benefits:
!"roved "roductivity
o 0igh1level object1oriented AP
o .ess Java code to write
o 5o 34. to write
!"roved "erfor!ance
o 3ophisticated caching
o .a(' loading
o 6ager loading
!"roved !aintainability
o A lot less code to write
!"roved "ortability
o ORM framewor) generates database1specific 34. for 'ou
#.What $oes Hibernate %i!"lify?
0ibernate simplifies:
3aving and retrieving 'our domain objects
Ma)ing database column and table name changes
!entrali(ing pre save and post retrieve logic
!omple$ joins for retrieving related items
3chema creation from object model
&.What is the need for Hibernate '!l !a""in( file?
0ibernate mapping file tells 0ibernate which tables and columns to use to load and store objects. +'pical mapping file loo) as follows:
).What are the !ost co!!on !ethods of Hibernate confi(uration?
+he most common methods of 0ibernate configuration are:
Programmatic configuration
2M. configuration ,hibernate.cfg.xml-
*.What are the i!"ortant ta(s of'!l?
&ollowing are the important tags of hibernate.cfg.$ml:
1+.What are the ,ore interfaces are of Hibernate fra!e-ork?
+he five core interfaces are used in just about ever' 0ibernate application. "sing these interfaces* 'ou can store and retrieve persistent objects and
control transactions.
3ession interface
3ession&actor' interface
!onfiguration interface
+ransaction interface
4uer' and !riteria interfaces
11.What role does the %ession interface "lay in Hibernate?
+he 3ession interface is the primar' interface used b' 0ibernate applications. t is a single1threaded* short1lived object representing a conversation
between the application and the persistent store. t allows 'ou to create %uer' objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
%ession interface role:
7raps a J#/! connection
&actor' for +ransaction
0olds a mandator' ,first1level- cache of persistent objects* used when navigating the object graph or loo)ing up objects b' identifier
12.What role does the %ession.actory interface "lay in Hibernate?
+he application obtains 3ession instances from a 3ession&actor'. +here is t'picall' a single 3ession&actor' for the whole application89:reated during
application initiali(ation. +he 3ession&actor' caches generate 34. statements and other mapping metadata that 0ibernate uses at runtime. t also holds
cached data that has been read in one unit of wor) and ma' be reused in a future unit of wor)
SessionFactory sessionFactory = configuration.buildSessionFactory();
13.What is the (eneral flo- of Hibernate co!!unication -ith R$/M%?
+he general flow of 0ibernate communication with R#/M3 is :
.oad the 0ibernate configuration file and create configuration object. t will automaticall' load all hbm mapping files
!reate session factor' from configuration object
;et one session from this session factor'
!reate 04. 4uer'
6$ecute %uer' to get list containing Java objects
14.What is Hibernate 0uery 1an(ua(e 2H013?
0ibernate offers a %uer' language that embodies a ver' powerful and fle$ible mechanism to %uer'* store* update* and retrieve objects from a database.
+his language* the 0ibernate %uer' .anguage ,04.-* is an object1oriented e$tension to 34..
15.Ho- do you !a" 4ava Ob5ects -ith $atabase tables?
&irst we need to write Java domain objects ,beans with setter and getter-.
7rite hbm.$ml* where we map java class to table and database columns to Java class variables.
6'a!"le :
<class name=com.test.!ser table=user>
<property column=!S"#$%&'" length=())
name=user%ame not-null=true type=*a+a.lang.String,>
<property column=!S"#$-&SS./#0 length=())
name=user-ass1ord not-null=true type=*a+a.lang.String,>
1#.What7s the difference bet-een load23 and (et23?
load,- vs. get,- :1
load23 (et23
Onl' use the load() method if 'ou are sure that the object e$ists. f 'ou are not sure that the object e$ists* then use one of the get() methods.
load() method will throw an e$ception if the uni%ue id is not found in the database. get() method will return null if the uni%ue id is not found in the database.
load() just returns a pro$' b' default and database won<t be hit until the pro$' is first invo)ed. get() will hit the database immediatel'.
1&.What is the difference bet-een and !er(e and u"date ?
"se update() if 'ou are sure that the session does not contain an alread' persistent instance with the same identifier* and merge() if 'ou want to merge
'our modifications at an' time without consideration of the state of the session.
1).Ho- do you define se8uence (enerated "ri!ary key in hibernate?
"sing =generator> tag.
<id column=!S"#$20 name=id type=*a+a.lang.3ong>
<generator class=se4uence>
<param name=table>S"5!"%6"$%&'"<,param>
1*.$efine cascade and inverse o"tion in one9!any !a""in(?
cascade 1 enable operations to cascade to child entities.
inverse 1 mar) this collection as the @inverse@ end of a bidirectional association.
6ssentiall' @inverse@ indicates which end of a relationship should be ignored* so when persisting a parent who has a collection of children* should 'ou as)
the parent for its list of children* or as) the children who the parents areB
2+.What do you !ean by :a!ed ; %01 8uery?
5amed 34. %ueries are defined in the mapping $ml document and called wherever re%uired.
<s4l-4uery name = empdetails>
<return alias=emp class=com.test."mployee,>
S"3"67 emp."'-$20 &S 8emp.empid9:
emp."'-$&00#"SS &S 8emp.address9:
emp."'-$%&'" &S 8emp.name9
F#/' "mployee "'- .;"#" emp.%&'" 32<" =name
nvo)e 5amed 4uer' :
3ist people = session.get%amed5uery(empdetails)
.setString(7om>rady: name)
21.Ho- do you invoke %tored =rocedures?
<s4l-4uery name=select&ll"mployees$S- callable=true>
<return alias=emp class=employee>
<return-property name=empid column="'-$20,>
<return-property name=name column="'-$%&'",>
<return-property name=address column="'-$&00#"SS,>
8 @ = call select&ll"mployees() 9
22.6'"lain ,riteria >=
!riteria is a simplified AP for retrieving entities b' composing !riterion objects. +his is a ver' convenient approach for functionalit' li)e @search@ screens
where there is a variable number of conditions to be placed upon the result set.
6'a!"le :
3ist employees = session.create6riteria("mployee.class)
.add(#estrictions.liAe(name: aB) )
.add(#estrictions.liAe(address: >oston))
.add/rder(/rder.asc(name) )
23.$efine Hibernate?e!"late?
org.springframe1orA.orm.hibernate.;ibernate7emplate is a helper class which provides different methods for %uer'ing/retrieving data from the
database. t also converts chec)ed 0ibernate6$ceptions into unchec)ed #ataAccess6$ceptions.
24.What are the benefits does Hibernate?e!"late "rovide?
+he benefits of 0ibernate+emplate are :
;ibernate7emplate* a 3pring +emplate class simplifies interactions with 0ibernate 3ession.
!ommon functions are simplified to single method calls.
3essions are automaticall' closed.
6$ceptions are automaticall' caught and converted to runtime e$ceptions.
25.Ho- do you s-itch bet-een relational databases -ithout code chan(es?
"sing 0ibernate 34. #ialects * we can switch databases. 0ibernate will generate appropriate h%l %ueries based on the dialect defined.
2#.f you -ant to see the Hibernate (enerated %01 state!ents on console@ -hat should -e do?
n 0ibernate configuration file set as follows:
<property name=sho1$s4l>true<,property>
2&.What are derived "ro"erties?
+he properties that are not mapped to a column* but calculated at runtime b' evaluation of an e$pression are called derived properties. +he e$pression
can be defined using the formula attribute of the element.
2).What is co!"onent !a""in( in Hibernate?
A component is an object saved as a value* not as a reference
A component can be saved directl' without needing to declare interfaces or identifier properties
Re%uired to define an empt' constructor
3hared references not supported
2*.What is the difference bet-een sorted and ordered collection in hibernate?
sorted collection vs. order collection :1
31.Wh at is
advanta(e of Hibernate over 5dbc?
0ibernate Cs. J#/! :1
sorted collection order collection
A sorted collection is sorting a collection b' utili(ing the sorting features provided
b' the Java collections framewor). +he sorting occurs in the memor' of JCM
which running 0ibernate* after the data being read from database using java
Order collection is sorting a collection b' specif'ing the order1b' clause for
sorting this collection when retrieval.
f 'our collection is not large* it will be more efficient wa' to sort it. f 'our collection is ver' large* it will be more efficient wa' to sort it .
JDBC Hibernate
7ith J#/!* developer has to write code to map
an object modelDs data representation to a
relational data model and its corresponding
database schema.
0ibernate is fle$ible and powerful ORM solution to
map Java classes to database tables. 0ibernate
itself ta)es care of this mapping using 2M. files so
developer does not need to write code for this.
7ith J#/!* the automatic mapping of Java
objects with database tables and vice versa
conversion is to be ta)en care of b' the
developer manuall' with lines of code.
0ibernate provides transparent persistence and
developer does not need to write code e$plicitl' to
map database tables tuples to application objects
during interaction with R#/M3.
J#/! supports onl' native 3tructured 4uer'
.anguage ,34.-. #eveloper has to find out the
efficient wa' to access database* i.e. to select
effective %uer' from a number of %ueries to
perform same tas).
0ibernate provides a powerful %uer' language
0ibernate 4uer' .anguage ,independent from t'pe
of database- that is e$pressed in a familiar 34. li)e
s'nta$ and includes full support for pol'morphic
%ueries. 0ibernate also supports native 34.
statements. t also selects an effective wa' to
perform a database manipulation tas) for an
Application using J#/! to handle persistent
data ,database tables- having database specific
code in large amount. +he code written to map
table data to application objects and vice
versa is actuall' to map table fields to object
properties. As table changed or database
changed then it<s essential to change object
structure as well as to change code written to
map table1to1object/object1to1table.
0ibernate provides this mapping itself. +he actual
mapping between tables and application objects is
done in 2M. files. f there is change in #atabase or
in an' table then the onl' need to change 2M. file
7ith J#/!* it is developer<s responsibilit' to
handle J#/! result set and convert it to Java
objects through code to use this persistent
data in application. 3o with J#/!* mapping
between Java objects and database tables is
done manuall'.
0ibernate reduces lines of code b' maintaining
object1table mapping itself and returns result to
application in form of Java objects. t relieves
programmer from manual handling of persistent
data* hence reducing the development time and
maintenance cost.
7ith J#/!* caching is maintained b' hand1
0ibernate* with +ransparent Persistence* cache is
set to application wor) space. Relational tuples are
moved to this cache as a result of %uer'. t
improves performance if client application reads
same data man' times for same write. Automatic
+ransparent Persistence allows the developer to
concentrate more on business logic rather than this
application code.
n J#/! there is no chec) that alwa's ever'
0ibernate enables developer to define version t'pe
field to application* due to this defined field
0ibernate updates version field of database table
ever' time relational tuple is updated in form of
Java class object to that table. 3o if two users
32.What are the ,ollection ty"es in Hibernate ?
33.What are the -ays to e'"ress 5oins in H01?
04. provides four wa's of e$pressing ,inner and outer- joins:1
An implicit association join
An ordinar' join in the &ROM clause
A fetch join in the &ROM clause.
A theta-style join in the 706R6 clause.
34.$efine cascade and inverse o"tion in one9!any !a""in(?
cascade 1 enable operations to cascade to child entities.
inverse 1 mar) this collection as the @inverse@ end of a bidirectional association.
6ssentiall' @inverse@ indicates which end of a relationship should be ignored* so when persisting a parent who has a collection of children* should 'ou as)
the parent for its list of children* or as) the children who the parents areB
35.What is Hibernate "ro'y?
+he proxy attribute enables la(' initiali(ation of persistent instances of the class. 0ibernate will initiall' return !;./ pro$ies which implement the
named interface. +he actual persistent object will be loaded when a method of the pro$' is invo)ed.
3#.Ho- can Hibernate be confi(ured to access an instance variable directly and not throu(h a
setter !ethod ?
/' mapping the propert' with access?@field@ in 0ibernate metadata. +his forces hibernate to b'pass the setter method and access the instance variable
directl' while initiali(ing a newl' loaded object.
3&.Ho- can a -hole class be !a""ed as i!!utable?
Mar) the class as mutable?@false@ ,#efault is true-*. +his specifies that instances of the class are ,not- mutable. mmutable classes* ma' not be updated or
deleted b' the application.
3).What is the use of dyna!ic9insert and dyna!ic9u"date attributes in a class !a""in(?
!riteria is a simplified AP for retrieving entities b' composing !riterion objects. +his is a ver' convenient approach for functionalit' li)e @search@ screens
where there is a variable number of conditions to be placed upon the result set.
dynamic-update ,defaults to false-: 3pecifies that !-0&7" 34. should be generated at runtime and contain onl' those columns whose values
have changed
dynamic-insert ,defaults to false-: 3pecifies that 2%S"#7 34. should be generated at runtime and contain onl' the columns whose values are
not null.
3*.What do you !ean by fetchin( strate(y ?
A fetching strategy is the strateg' 0ibernate will use for retrieving associated objects if the application needs to navigate the association. &etch
strategies ma' be declared in the O/R mapping metadata
a* or over1ridden b' a particular 04. or6riteria %uer'.
4+.What is auto!atic dirty checkin(?
Automatic dirt' chec)ing is a feature that saves us the effort of e$plicitl' as)ing 0ibernate to update the database when we modif' the state of an object
inside a transaction.
41.What is transactional -rite9behind?
0ibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign )e' constraint violations but is still sufficientl'
predictable to the user. +his feature is called transactional write1behind.
42.What are ,allback interfaces?
!allbac) interfaces allow the application to receive a notification when something interesting happens to an objectEfor e$ample* when an object is
loaded* saved* or deleted. 0ibernate applications donDt need to implement these callbac)s* but the'Dre useful for implementing certain )inds of generic
43.What are the ty"es of Hibernate instance states ?
+hree t'pes of instance states:
+ransient 1+he instance is not associated with an' persistence conte$t
Persistent 1+he instance is associated with a persistence conte$t
#etached 1+he instance was associated with a persistence conte$t which has been closed F currentl' not associated
44.What are the differences bet-een 64/ 3.+ A Hibernate
0ibernate Cs 6J/ G.H :1
Hibernate EJB 3.0
%essionF!ache or collection of loaded objects relating to a single unit of wor)
=ersistence ,onte't13et of entities that can be managed b' a given 6ntit'Manager is defined b' a
persistence unit
B$oclet >nnotations used to support Attribute Oriented Programming 4ava 5.+ >nnotations used to support Attribute Oriented Programming
$efines H01 for e$pressing %ueries to the database $efines 64/ 01 for e$pressing %ueries
%u""orts 6ntity Relationshi"s through mapping files and annotations in Java#oc %u""ort 6ntity Relationshi"s through Java I.H annotations
=rovides a =ersistence Mana(er >= e$posed via the 3ession* 4uer'* !riteria* and +ransaction AP =rovides and 6ntity Mana(er nterface for managing !R"# operations for an 6ntit'
=rovides callback su""ort through lifec'cle* interceptor* and validatable interfaces =rovides callback su""ort through 6ntit' .istener and !allbac) methods
6ntity Relationshi"s are unidirectional. /idirectional relationships are implemented b' two unidirectional
6ntity Relationshi"s are bidirectional or unidirectional
45.What are the ty"es of inheritance !odels in Hibernate?
+here are three t'pes of inheritance models in 0ibernate:
+able per class hierarch'
+able per subclass
+able per concrete class
Q. How will you configure Hibernate?
The configuration files hibernate.cfg.xml (or and mapping files *.hbm.xml are used by the Configuration class to create
(i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary
interface for the persistence serice.
! hibernate.cfg.xml (alternatiely can use" These two files are used to configure the hibernate seice (connection drier
class, connection #$%, connection username, connection password, dialect etc). &f both files are present in the classpath then hibernate.cfg.xml
file oerrides the settings found in the file.
! 'apping files (*.hbm.xml)" These files are used to map persistent ob(ects to a relational database. &t is the best practice to store each ob(ect in
an indiidual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to
manage and maintain. The naming conention is to use the same name as the persistent ()*+*) class name. For example ,ccount.class will
hae a mapping file named ,ccount.hbm.xml. ,lternatiely hibernate annotations can be used as part of your persistent class code instead of the
*.hbm.xml files.
Q. What is a SessionFactory? Is it a thread-safe object?
SessionFactory is -ibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and re.uest for
sessions and immutable cache of compiled mappings for a single database. , SessionFactory is usually only built once at startup. SessionFactory
should be wrapped in some /ind of singleton so that it can be easily accessed in an application code.
SessionFactory sessionFactory 0 new Configuration().configure().buildSessionfactory()1
Q. What is a Session? an you share a session object between different theads?
Session is a light weight and a non2threadsafe ob(ect (3o, you cannot share it between threads) that represents a single unit2of2wor/ with the
database. Sessions are opened by a SessionFactory and then are closed when all wor/ is complete. Session is the primary interface for the
persistence serice. , session obtains a database connection la4ily (i.e. only when re.uired). To aoid creating too many sessions Thread%ocal
class can be used as shown below to get the current session no matter how many times you ma/e call to the currentSession() method.
public class -ibernate#til 6
public static final Thread%ocal local 0 new Thread%ocal()1
public static Session currentSession() throws -ibernate7xception 6
Session session 0 (Session) local.get()1
88open a new session if this thread has no session
if(session 00 null) 6
session 0 sessionFactory.openSession()1
return session1
&t is also ital that you close your session after your unit of wor/ completes. 3ote" :eep your -ibernate Session ,)& handy.
Q. What are the benefits of detached objects?
;etached ob(ects can be passed across layers all the way up to the presentation layer without haing to use any ;T*s (;ata Transfer *b(ects).
<ou can later on re2attach the detached ob(ects to another session.
Q. What are the !ros and cons of detached objects?
! =hen long transactions are re.uired due to user thin/2time, it is the best practice to brea/ the long transaction up into two or more
transactions. <ou can use detached ob(ects from the first transaction to carry data all the way up to the presentation layer. These detached
ob(ects get modified outside a transaction and later on re2attached to a new transaction ia another session.
! &n general, wor/ing with detached ob(ects is .uite cumbersome, and better to not clutter up the session with them if possible. &t is better to
discard them and re2fetch them on subse.uent re.uests. This approach is not only more portable but also more efficient because 2 the ob(ects
hang around in -ibernate>s cache anyway.
! ,lso from pure rich domain drien design perspectie it is recommended to use ;T*s (;ataTransfer*b(ects) and ;*s (;omain*b(ects) to
maintain the separation between Serice and #& tiers.
Q. How does Hibernate distinguish between transient #i.e. newly instantiated$ and detached objects?
! -ibernate uses the ersion property, if there is one.
! &f not uses the identifier alue. 3o identifier alue means a new ob(ect. This does wor/ only for -ibernate managed surrogate /eys. ;oes not
wor/ for natural /eys and assigned (i.e. not managed by -ibernate) surrogate /eys.
! =rite your own strategy with &
Q. What is the difference between the session.get#$ %ethod and the session.load#$ %ethod?
?oth the session.get(..) and session.load() methods create a persistent ob(ect by loading the re.uired ob(ect from the database. ?ut if there was not such
ob(ect in the database then the method session.load(..) throws an exception whereas session.get(5) returns null.
Q. What is the difference between the session.u!date#$ %ethod and the session.loc&#$ %ethod?
?oth of these methods and sae*r#pdate() method are intended for reattaching a detached ob(ect. The session.loc/() method simply reattaches the
ob(ect to the session without chec/ing or updating the database on the assumption that the database in sync with the detached ob(ect. &t is the best
practice to use either session.update(..) or session.sae*r#pdate(). #se session.loc/() only if you are absolutely sure that the detached ob(ect is in sync
with your detached ob(ect or if it does not matter because you will be oerwriting all the columns that would hae changed later on within the same
'ote: =hen you reattach detached ob(ects you need to ma/e sure that the dependent ob(ects are reatched as well.
Q. How would you reatach detached objects to a session when the sa%e object has already been loaded into the session?
<ou can use the session.merge() method call.
Q. What are the general considerations or best !ractices for defining your Hibernate !ersistent classes?
@.<ou must hae a default no2argument constructor for your persistent classes and there should be getAAA() (i.e accessor8getter) and setAAA( i.e.
mutator8setter) methods for all your persistable instance ariables.
B.<ou should implement the e.uals() and hashCode() methods based on your business /ey and it is important not to use the id field in your e.uals() and
hashCode() definition if the id field is a surrogate /ey (i.e. -ibernate managed identifier). This is because the -ibernate only generates and sets the field
when saing the ob(ect.
C. &t is recommended to implement the Seriali4able interface. This is potentially useful if you want to migrate around a multi2processor cluster.
D.The persistent class should not be final because if it is final then la4y loading cannot be used by creating proxy ob(ects.
E.#se A;oclet tags for generating your *.hbm.xml files or ,nnotations (+;: @.E onwards), which are less erbose than *.hbm.xml files.
=ould li/e to hear more .uestions and answers from the readers.....
1. Whats Hibernate?
Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration
files in XML format. fter java objects mapping to !atabase tables" !atabase is use! an! han!le! using Java objects
without writing comple# !atabase $ueries.
%. What is ORM?
ORM &Object Relational Mapping' is the fun!amental concept of Hibernate framework which maps !atabase tables
with Java Objects an! then provi!es various ()*s to perform !ifferent t+pes of operations on the !ata tables.
,. How properties of a class are appe! to the col"ns of a !atabase table in Hibernate?
Mappings between class properties an! table columns are specifie! in XML file as in the below e#ample-
<@xml +ersion=C.?@> <D0/67E-" hibernate-mapping -!>326



<class name=department6lass table=7>3$0"-7>

<property name=dept column=department$name>

<property name=0escription column=department$details,>

<many-to-one name=nxt-er cascade=all column=%xt-er2d,>


/. Whats the "sa#e of Confi#"ration $nterface in hibernate?
0onfiguration interface of hibernate framework is use! to configure hibernate. )t*s also use! to bootstrap hibernate.
Mapping !ocuments of hibernate are locate! using this interface.
1. How can we "se new c"sto interfaces to enhance f"nctionalit% of b"ilt&in interfaces of hibernate?
2e can use e#tension interfaces in or!er to a!! an+ re$uire! functionalit+ which isn*t supporte! b+ built3in interfaces.
4. 'ho"l! all the appin# files of hibernate ha(e .hb.)l e)tension to wor* properl%?
5o" having .hbm.#ml e#tension is a convention an! not a re$uirement for hibernate mapping file names. 2e can
have an+ e#tension for these mapping files.
6. How !o we create session factor% in hibernate?
7o create a session factor+ in hibernate" an object of configuration is create! first which refers to the path of
configuration file an! then for that configuration" session factor+ is create! as given in the e#ample below-
6onfiguration config = ne1 6onfiguration();
config.set-roperties( System.get-roperties() );
SessionFactory sessions = config.buildSessionFactory();
8. What are +OJOs an! whats their si#nificance?
(OJOs& (lain Ol! Java Objects' are java beans with proper getter an! setter metho!s for each an! ever+ properties.
9se of (OJOs instea! of simple java classes results in an efficient an! well constructe! co!e.
:. Whats H,-?
H;L is the $uer+ language use! in Hibernate which is an e#tension of <;L. H;L is ver+ efficient" simple an! fle#ible
$uer+ language to !o various t+pe of operations on relational !atabase without writing comple# !atabase $ueries.
1=. How can we in(o*e store! proce!"res in hibernate?
)n hibernate we can e#ecute store! proce!ures using co!e as below-
<s4l-4uery name=getStudents callable=true>
<return alias=st class=Student>
<return-property name=std$id column=S70$20,>
<return-property name=s$name column=S70$%&'",>
<return-property name=s$dept column=S70$0"-&#7'"%7,>
8 @ = call selectStudents() 9
11. What is criteria .+$?
0riteria is a simple +et powerful () of hibernate which is use! to retrieve entities through criteria object composition.
1%. What are the benefits of "sin# Hibernate teplate?
>ollowing are some ke+ benefits of using Hibernate template-
a. <ession closing is automate!.
b. )nteraction with hibernate session is simplifie!.
c. ?#ception han!ling is automate!.
1,. How can we see hibernate #enerate! ',- on console?
2e nee! to a!! following in hibernate configuration file to enable viewing <;L on the console for !ebugging
<property name=sho1$s4l>true<,property>
1/. What are the two t%pes of collections in hibernate?
>ollowing are the two t+pes of collections in hibernate-
a. <orte! 0ollection
b. Or!er 0ollection
11. Whats the !ifference between an!!ate/0 etho!s in hibernate?
<essionsave&' metho! saves a recor! onl+ if it*s uni$ue with respect to its primar+ ke+ an! will fail to insert if primar+
ke+ alrea!+ e#ists in the table.
saveOr9p!ate&' metho! inserts a new recor! if primar+ ke+ is uni$ue an! will up!ate an e#isting recor! if primar+
ke+ e#ists in the table alrea!+.
14. What the benefits are of hibernate o(er JDBC?
a. Hibernate can be use! seamlessl+ with an+ t+pe of !atabase as its !atabase in!epen!ent while in case of J@A0"
!eveloper has to write !atabase specific $ueries.
b. 9sing hibernate" !eveloper !oesn*t nee! to be an e#pert of writing comple# $ueries as H;L simplifies $uer+
writing process while in case of J@A0" its job of !eveloper to write an! tune $ueries.
c. )n case of hibernate" there is no nee! to create connection pools as hibernate !oes all connection han!ling
automaticall+ while in case of J@A0" connection pools nee! to be create!.
16. How can we #et hibernate statistics?
2e can get hibernate statistics using get<tatistics&' metho! of <ession>actor+ class as shown below-
18. What is transient instance state in Hibernate?
)f an instance is not associate! with an+ persistent conte#t an! also" it has never been associate! with an+ persistent
conte#t" then it*s sai! to be in transient state.
1:. How can we re!"ce !atabase write action ties in Hibernate?
Hibernate provi!es !irt+ checking feature which can be use! to re!uce !atabase write times. @irt+ checking feature
of hibernate up!ates onl+ those fiel!s which re$uire a change while keeps others unchange!.
%=. Whats the "sa#e of callbac* interfaces in hibernate?
0allback interfaces of hibernate are useful in receiving event notifications from objects. >or e#ample" when an object
is loa!e! or !elete!" an event is generate! an! notification is sent using callback interfaces.
%1. When an instance #oes in !etache! state in hibernate?
2hen an instance was earlier associate! with some persistent conte#t &e.g. a table' an! is no longer associate!" it*s
calle! to be in !etache! state.
%%. What the fo"r ORM le(els are in hibernate?
>ollowing are the four ORM levels in hibernate-
a. (ure Relational
b. Light Object Mapping
c. Me!ium Object Mapping
!. >ull Object Mapping
%,. Whats transaction ana#eent in hibernate? How it wor*s?
7ransaction management is the process of managing a set of statements or comman!s. )n hibernateB transaction
management is !one b+ transaction interface as shown in below co!e-
Session s = null;
7ransaction tr = null;
try 8
s = sessionFactory.openSession();
tr = s.begin7ransaction();
9 catch (#untime"xception exc) 8
9 finally 8
%/. What the two etho!s are of hibernate confi#"ration?
2e can use an+ of the following two metho!s of hibernate configuration-
a. XML base! configuration & using hibernate.cfg.#ml file'
b. (rogrammatic configuration & 9sing co!e logic'
%1. What is the !efa"lt cache ser(ice of hibernate?
Hibernate supports multiple cache services like ?H0ache" O<0ache" <2RM0ache an! 7ree0ache an! !efault
cache service of hibernate is ?H0ache.
%4. What are the two appin# associations "se! in hibernate?
)n hibernateB we have following two t+pes of mapping associations between entities-
a. One3to3One ssociation
b. Man+3to3Man+ ssociation
%6. Whats the "sa#e of Hibernate ,BC .+$?
Hibernate ;uer+ A+ 0riteria &;A0' () is use! to create $ueries b+ manipulation of criteria objects at runtime.
%8. $n how an% wa%s2 ob3ects can be fetche! fro !atabase in hibernate?
Hibernate provi!es following four wa+s to fetch objects from !atabase-
a. 9sing H;L
b. 9sing i!entifier
c. 9sing 0riteria ()
!. 9sing <tan!ar! <;L
%:. How priar% *e% is create! b% "sin# hibernate?
@atabase primar+ ke+ is specifie! in the configuration file hbm.#ml. Cenerator can also be use! to specif+ how
primar+ ke+ is being create! in the !atabase.
)n the below e#ample" !ept)! acts as primar+ ke+-
<id name=dept2d type=string >
<column name=column2d length=G?,>
,=. How can we reattach an% !etache! ob3ects in Hibernate?
Objects which have been !etache! an! are no longer associate! with an+ persistent entities can be reattache! b+
calling session.merge&' metho! of session class.
,1. What are !ifferent wa%s to !isable hibernate secon! le(el cache?
Hibernate secon! level cache can be !isable! using an+ of the following wa+s-
a. A+ setting useDsecon!DlevelDcache as false.
b. A+ using 00H?MO@?.)C5OR?
c. 9sing cache provi!er as org.hibernate.cache.5o0ache(rovi!er
,%. What is ORM eta!ata?
ll the mapping between classes an! tables" properties an! columns" Java t+pes an! <;L t+pes etc is !efine! in
ORM meta!ata.
,,. Which one is the !efa"lt transaction factor% in hibernate?
2ith hibernate ,.%" !efault transaction factor+ is J@A07ransaction>actor+.
,/. Whats the role of JM4 in hibernate?
Java pplications an! components are manage! in hibernate b+ a stan!ar! () calle! JMX (). JMX provi!es tools
for !evelopment of efficient an! robust !istribute!" web base! solutions.
,1. How can we bin! hibernate session factor% to J5D$ ?
Hibernate session factor+ can be boun! to J5@) b+ making configuration changes in hibernate.cfg file.
,4. $n how an% wa%s ob3ects can be i!entifie! in Hibernate?
Object i!entification can be !one in hibernate in following three wa+s-
a. 9sing Object )!entit+- 9sing EE operator.
b. 9sing Object ?$ualit+- 9sing e$uals&' metho!.
c. 9sing !atabase i!entit+- Relational !atabase objects can be i!entifie! if the+ represent same row.
,6. What !ifferent fetchin# strate#ies are of hibernate?
>ollowing fetching strategies are available in hibernate-
1. Join >etching
%. Aatch >etching
,. <elect >etching
/. <ub3select >etching
,8. How appin# of 3a(a ob3ects is !one with !atabase tables?
7o map java objects with !atabase tables" we nee! to have Java beans properties names same as column names of
a !atabase table. 7hen mapping is provi!e! in hbm.#ml file as given below-
<class name=Student table=tbl$student>
<property column=studentname length=())
name=student%ame not-null=true type=*a+a.lang.String,>
<property column=student0isciplne length=())
name=student0iscipline not-null=true type=*a+a.lang.String,>
,:. What are !eri(e! properties in hibernate?
@erive! properties are those properties which are not mappe! to an+ columns of a !atabase table. <uch properties
are calculate! at runtime b+ evaluation of an+ e#pressions.
/=. What is eant b% a 5ae! ',- ,"er% in hibernate an! how its "se!?
5ame! <;L $ueries are those $ueries which are !efine! in mapping file an! are calle! as re$uire! an+where.
>or e#ample" we can write a <;L $uer+ in our XML mapping file as follows-
<s4l-4uery name = studentdetails>
<return alias=std,>
S"3"67 std.S7!0"%7$20 &S 8std.S7!0"%7$209:
std.S7!0"%7$02S62-32%" &S 8std.discipline9:

F#/' Student std .;"#" std.%&'" 32<" =name
7hen this $uer+ can be calle! as follows-
3ist students = session.get%amed5uery(Famp;4uot;studentdetailsFamp;4uot;)
.setString(Famp;4uot;7om>radyFamp;4uot;: name)
/1. Whats the !ifference between loa!/0 an! #et/0 etho! in hibernate?
Loa!&' metho!s results in an e#ception if the re$uire! recor!s isn*t foun! in the !atabase while get&' metho! returns
null when recor!s against the i! isn*t foun! in the !atabase.
<o" i!eall+ we shoul! use Loa!&' metho! onl+ when we are sure about e#istence of recor!s against an i!.
/%. Whats the "se of (ersion propert% in hibernate?
Fersion propert+ is use! in hibernate to know whether an object is in transient state or in !etache! state.
/,. What is attrib"te oriente! pro#rain#?
)n ttribute oriente! programming" a !eveloper can a!! Meta !ata &attributes' in the java source co!e to a!! more
significance in the co!e. >or Java &hibernate'" attribute oriente! programming is enable! b+ an engine calle!
//. Whats the "se of session.loc*/0 in hibernate?
session.lock&' metho! of session class is use! to reattach an object which has been !etache! earlier. 7his metho! of
reattaching !oesn*t check for an+ !ata s+nchroniGation in !atabase while reattaching the object an! hence ma+ lea!
to lack of s+nchroniGation in !ata.
/1. Does hibernate s"pport pol%orphis?
Hes" hibernate full+ supports pol+morphism. (ol+morphism $ueries an! pol+morphism associations are supporte! in
all mapping strategies of hibernate.
/4. What the three inheritance o!els are of hibernate?
Hibernate has following three inheritance mo!els-
a. 7ables (er 0oncrete 0lass
b. 7able per class hierarch+
c. 7able per sub3class
/6. How can we ap the classes as i"table?
)f we !on*t want an application to up!ate or !elete objects of a class in hibernate" we can make the class as
immutable b+ setting mutableEfalse
/8. Whats #eneral hibernate flow "sin# RDBM'?
Ceneral hibernate flow involving R@AM< is as follows-
a. Loa! configuration file an! create object of configuration class.
b. 9sing configuration object" create session>actor+ object.
c. >rom session>actor+" get one session.
!. 0reate H;L $uer+.
e. ?#ecute H;L $uer+ an! get the results. Results will be in the form of a list.
/:. What is -i#ht Ob3ect Mappin#?
Light Object Mapping is one of the levels of ORM $ualit+ in which all entities are represente! as classes an! the+ are
mappe! manuall+.
1=. Whats !ifference between ana#e! associations an! hibernate associations?
Manage! associations relate to container management persistence an! are bi3!irectional while hibernate
associations are uni!irectional.