Google

Dec 7, 2010

15+ Hibernate Interview Questions and Answers: Overview

If you ask me  to list two frameworks that are very prevalently used in Java projects and very popular in job interviews, it would be (1) Spring framework (2) Hibernate framework.

Q. How will you configure Hibernate?
A. The configuration files hibernate.cfg.xml (or hibernate.properties) 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 service.

hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual 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 convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively, 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?
A. SessionFactory is Hibernate's concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration( ).configure( ).buildSessionfactory( );


Q. What is a Session? Can you share a session object between different threads?
A. Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession( ) method.

public class HibernateUtil { 

    public static final ThreadLocal local = new ThreadLocal(); 

    public static Session currentSession() throws HibernateException { 
         Session session = (Session) local.get(); 
         //open a new session if this thread has no session 
        if(session == null) { 
            session = sessionFactory.openSession(); 
            local.set(session); 
       } 
        return session; 
    } 
} 


It is also vital that you close your session after your unit of work completes.

Note: Keep your Hibernate Session API handy. Quite often, hibernate is used with Spring framework, using the Template design pattern.


Q. Explain hibernate object states? Explain hibernate objects life cycle?
A.

Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects  synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List  etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item  from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.  

Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save( ), session.persist( )  etc.


Q. What are the benefits of detached objects?
A.

Pros:
  • When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.
Cons:
  • In general, working with detached objects is quite cumbersome, and it is better not to clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
  • Also from pure rich domain driven design perspective, it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.


Q. When does an object become detached?
A.

Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId);//”myCar” is a persistent object at this stage.
session1.close();          //once the session is closed “myCar” becomes a detached object

you can now pass the “myCar” object all the way upto the presentation tier. It can be modified without any effect to your database table.

myCar.setColor(“Red”);    //no effect on the database

When you are ready to persist this change to the database, it can be reattached to another session as shown below:

Session session2 = sessionFactory.openSession(); 
Transaction tx = session2.beginTransaction();
session2.update(myCar);           //detached object ”myCar” gets re-attached 
tx.commit();                      //change is synchronized with the database.
session2.close()


Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
A.
  • Hibernate uses the "version" property, if there is one.
  • If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
  • Write your own strategy with Interceptor.isUnsaved( ).
Note: When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.


Note: Extracted from my book "Java/J2EE Job Interview Companion".


More Hibernate Related Interview Questions and Answers


If you want to get a better handle on Hibernate

Labels:

30 Comments:

Anonymous Anonymous said...

Great blog man !! Helps a lot !!

6:18 AM, March 05, 2012  
Anonymous Anonymous said...

great blog and post !!

Good job !!

Thnx !!!

6:19 AM, March 05, 2012  
Anonymous Anonymous said...

thanks for the great blog

6:08 AM, June 13, 2012  
Anonymous Anonymous said...

fantastic.. it was too helpful.

3:05 AM, July 03, 2012  
Anonymous Anonymous said...

very nice.. explaination is very good . Thanks a lot

4:34 PM, August 23, 2012  
Blogger ruksoft said...

Superb one!

3:50 AM, August 24, 2012  
Anonymous Anonymous said...

Good one...........

8:22 PM, September 06, 2012  
Anonymous Anonymous said...

Excellent.. it was too helpful.

11:07 PM, September 07, 2012  
Anonymous Anonymous said...

Nice blog! thanks

5:13 PM, September 16, 2012  
Anonymous Anonymous said...

where are remaining concepts man.........

10:16 PM, September 22, 2012  
Blogger Unknown said...

Did you go through the related links? I will add more and stay tuned.

9:52 AM, September 23, 2012  
Anonymous Anonymous said...

ok,thank you so much.............it's really very helpful to me.

8:53 PM, September 25, 2012  
Anonymous Anonymous said...

ok,thanks for this great blog

8:55 PM, September 25, 2012  
Blogger Natarajan said...

ya sure..pl post more
questions

10:40 PM, October 09, 2012  
Anonymous peter said...

pl post more questions

10:41 PM, October 09, 2012  
Blogger Unknown said...

will do, and stay tuned

12:10 AM, October 10, 2012  
Anonymous Jassu said...

Very nice collection, great work.

3:39 PM, October 11, 2012  
Anonymous Anonymous said...

Q) What is the real time scenario to use merge?
A) When there is a persistent object and is being modified in the ui by the user instead of having the session open you can detach the object and reattach when the user is done my calling merge().

Q) Diff between merge vs saveOrUpdate?
A) Like above merge is used when the a detached state object is changed and should be saved.
saveOrUpdate is only used when we have a object in persistent state.

8:46 AM, October 27, 2012  
Blogger Job Interview Question Answers said...

Nice post . . Very Usefull information

Dhung.com provid interview question and answer for all company.

10:42 PM, October 28, 2012  
Blogger Vishal said...

Good One...

10:46 PM, November 02, 2012  
Anonymous Anonymous said...

i would like your blog can you give more regarding real time senario
thanks a lot

7:10 PM, May 19, 2013  
Blogger Unknown said...

not sure what you mean by real time scenario. Do you mean where it is used?

11:28 PM, May 19, 2013  
Anonymous Anonymous said...

Consider a scenario.there is a text box.in which we are accepting comma separated string
eg..city is text box..
and user enters pune,delhi,banglore...user can enter more cities also.
so how to save these details into database using hibernate..
in database every city will be stored in one colmn..separately
fr eg.city 1 will be pune
city 2 will be delhi
and city 3 will be banglore..
and if user enter more cities then it should be increased..

4:18 PM, June 19, 2013  
Anonymous james said...

thanks a lot for nice post

4:29 AM, August 29, 2013  
Blogger Unknown said...

hello sir!!!!

write a post how a fresher can get a java job?

6:53 PM, November 09, 2013  
Blogger Unknown said...

Read the following posts on career tips:

1. http://java-success.blogspot.com.au/2010/12/handy-tips-to-get-some-work-experience.html
2. http://java-success.blogspot.com.au/2010/12/handy-job-hunting-tips-in-tough-times.html

9:34 PM, November 09, 2013  
Blogger Purnima Das said...

Thank you, Arulkumaran, for this post, it has been very helpful.

Purnima Das

7:56 PM, November 13, 2013  
Anonymous Anonymous said...

could it be possible as you are asking if yes please help us to understand it

9:57 PM, November 18, 2013  
Anonymous Anonymous said...

it is not bad

3:30 AM, May 09, 2014  
Anonymous Anonymous said...

Thank you, for this post, it has been very helpful.

1:46 AM, August 06, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home