Hibernate Interview Questions are asked on Java J2EE Interviews, mostly for
web based enterprise application development role. Success and acceptability of
Hibernate framework on Java world has made it one of the most popular Object
Relational Mapping (ORM) solution in Java technology stack. Hibernate frees you
from database specific coding and allows you to focus more on utilizing
powerful object oriented design principle
to implement core business logic. By using Hibernate you can switch between
database rather easily and also take advantage of out of box caching facilities
provided by Hibernate, in terms of second level cache and query cache. As you
know most of Java interview not only contains questions from core Java, but
also from other Java framework e.g. questions from Spring Framework
or Struts interview questions, based
upon projects requirements. Its good to prepare both Spring and Hibernate
questions quite well, if you are going to work on a project which uses
Hibernate as ORM. Check JD or Job description ,and if you see word Hibernate
anywhere, get ready to face some Hibernate questions.
Interview Question on Hibernate Framework
Here is my list of Hibernate interview question, which I have collected
from friends and colleagues. Hibernate is a popular Object Relational Mapping
framework and good knowledge of advantages offered by Hibernate along with
Hibernate Session API is key to do well in any Hibernate Interview.
Difference
between get and load in Hibernate?
get vs load is one of the most frequently asked Hibernate Interview
question, since correct understanding of both get() and load() is require
to effectively using Hibernate. Main difference between get and load is that,
get will hit the database if object is not found in the cache and returned
completely initialized object, which may involve several database call while load() method can
return proxy, if object is not found in cache and only hit database if any
method other than getId() is called. This can save lot of performance
in some cases. You can also see difference between get and load in
Hibernate for more differences and detailed discussion on this
question.
Difference
between save, persist and saveOrUpdate methods in Hibernate?
After get vs load, this is another Hibernate Interview question which
appears quite often. All three methods i.e. save(), saveOrUpdate() and persist() is used to
save objects into database, but has subtle differences e.g. save() can only
INSERT records but saveOrUpdate() can either INSERT or UPDATE records. Also,
return type of save() is a Serializable object,
while return type of persist() method is void. You can also check
save vs persist vs saveOrUpdate
for complete differences between them in hibernate.
What is
named SQL query in Hibernate?
This Hibernate Interview question is related to query functionality
provided by Hibernate. Named queries are SQL queries which are defined in
mapping document using <sql-query> tag and called using Session.getNamedQuery() method.
Named query allows you to refer a particular query by the name you provided, by
the way you can define named query in hibernate either by using annotations or
xml mapping file, as I said above. @NameQuery is used to
define single named query and @NameQueries is used to
define multiple named query in hibernate.
What is
SessionFactory in Hibernate? is SessionFactory thread-safe?
Another common Interview questions related to Hibernate framework. SessionFactory as name
suggest is a factory to create hibernate Session objects.
SessionFactory is often built during start-up and used by application code to
get session object. It acts as single data store and its also thread-safe so that multiple
thread can use same SessionFactory. Usually a Java JEE application
has just one SessionFactory, and individual threads, which are servicing
client’s request obtain hibernate Session instances from this factory, that’s
why any implementation of SessionFactory interface must be thread-safe.
Also internal state of SessionFactory, which contains all meta data
about Object/Relational mapping is Immutable and can not be
changed once created.
What is
Session in Hibernate? Can we share single Session among multiple threads in
Hibernate?
This is usually asked as follow-up question of previous Hibernate
Interview question. After SessionFactory its time for Session. Session represent
a small unit of work in Hibernate, they maintain connection with database and
they are not thread-safe, it means you can not share Hibernate Session
between multiple threads. Though Session obtains
database connection lazily it's good to close session as soon as you are done
with it.
What is
difference between sorted and ordered collection in hibernate?
This is one of the easy Hibernate interview question you ever face. A
sorted collection is sorted in memory by using Java Comparator, while a
ordered collection uses database's order by clause for
ordering. For large data set it's better to use ordered collection to avoid any
OutOfMemoryError in Java, by
trying to sort them in memory.
What is
difference between transient, persistent and detached object in Hibernate?
In Hibernate, Object can remain in three state transient, persistent or detached. An object which is associated with Hibernate
session is called persistent object. Any change in this object
will reflect in database based upon your flush strategy i.e. automatic flush
whenever any property of object change or explicit flushing by calling Session.flush() method. On
the other hand if an object which is earlier associated with Session, but
currently not associated with it are called detached object.
You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on
that session. Transient objects are newly created instance of persistence class,
which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to
make transient object persistent. Just remember, here transient doesn’t
represent transient keyword in Java,
which is altogether different thing.
What does
Session lock() method do in Hibernate?
This one is one of the tricky Hibernate Interview question, because
Session's lock() method reattach object without
synchronizing or updating with database. So you need to be very careful while
using lock() method. By the way you can always use Session's update() method to
sync with database during reattachment. Some time this Hibernate question is
also asked as what is difference between
Session's lock() and update() method. You can use this key point to answer
that question as well.
What is Second
level Cache in Hibernate?
This is one of the first interview question related to caching in Hibernate,
you can expect few more. Second level Cache is maintained at SessionFactory level and
can improve performance by saving few database round trip. Another
worth noting point is that second level cache is available to whole application
rather than any particular session.
What is
query cache in Hibernate ?
This question, Some times asked as a follow-up of last Hibernate
Interview question, QueryCache actually stores result of sql query
for future calls. Query cache can be used along with second level cache for
improved performance. Hibernate support various open source caching solution to
implement Query cache e.g. EhCache.
Why it's important to provide no argument constructor in Hibernate Entities?
Every Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API, by calling Class.newInstance() method. This method will throw InstantiationException if it doesn't found no argument constructor inside Entity class.
Can we make an Hibernate Entity Class final?
Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.
That's all on this list of Hibernate Interview questions and answer for
Java developers. No one can doubt popularity of Hibernate as ORM solution and
if you are going for a Java J2EE position, you can expect questions from
Hibernate. Especially Spring and Hibernate are two most popular Java framework
in JEE space. Don't forget to share any other Hibernate Interview Question,
which you have been asked and good enough to share with Java community.
16 comments :
I believe we need to include What is lazy initialization exception.. Which was asked thrice to me in interview.
one more: what is N+1 problem and strategies to avoid this
@inj rav, Those are really good question, I have also seen lazy initialization exception couple of times, will definitely include those.
@Surajtamang, Apart from re-attaching a transient object to session, Session.lock(Object object,LockMode lockMode) is also used to perform version check, they do this by acquiring an appropriate LockLevel e.g. LockLevel.READ for version check. Different lock modes are provided to prevent entity from being read and modified simultaneously from multiple source. By the way both overloaded version of lock()method is deprecated and it's advised to use buildLockRequest(LockMode).lock(object) method for similar purpose.
Hello, Can you please upload PDF version or let me know if there is any way to download these Hibernate interview Questions as PDF? Thanks
In Hibernate how can we change the database only by just changing the hibernate.cfg.xml,if so how can we handle migration issues.
It's JavaEE and for such a job interview I would assume questions about JPA and not the proprietary Hibernate API
Save, saveorupdate, persist for me the only correct answer is: broken by design
Seriously - if presented with these questions and a huge domain model, using Hibernate as persistence, think twice before applying for the job ...
What is difference b/w session.getCurrentSession() and session.openSession()?? please answer it in brief.
when we use criterian in hibernate ?
what about hibernate Polymorphism?
Difference b/w sessionFactory.getCurrentSession() and sessionFactory.openSession():
openSession() creates a new normal Session, that needs to be explicitly closed once the required operations are complete.
getCurrentSession() - introduced in Hibernate 3.0 - returns a Contextual Session, which is nothing but one Session per Transaction. The Session is automatically closed once the transaction is committed. Also, it enforces the developer to make sure he uses only one session one transaction policy that hibernate recommends. Make sure that you invoke this method from within a Transactional Context, else it may throw an Exception.
What design pattern does session factory uses? Answer is singleton. One object per application per database connection.
Hi Javin,
I found this Q&A "What does Session lock() method do in Hibernate?" not so clear. Can you please explain on this matter little more?
There is another question difference between update and merge.
Ans: Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session.
How object state changes from persistent to transient?
Ans: delete() method,
Please correct if its wrong, elaborate if anyone can.
Post a Comment