Search this Java developer blog:

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

30 comments:

  1. Great blog man !! Helps a lot !!

    ReplyDelete
  2. great blog and post !!

    Good job !!

    Thnx !!!

    ReplyDelete
  3. thanks for the great blog

    ReplyDelete
  4. fantastic.. it was too helpful.

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

    ReplyDelete
  6. Good one...........

    ReplyDelete
  7. Excellent.. it was too helpful.

    ReplyDelete
  8. Nice blog! thanks

    ReplyDelete
  9. where are remaining concepts man.........

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

    ReplyDelete
    Replies
    1. ok,thanks for this great blog

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

    ReplyDelete
  12. ya sure..pl post more
    questions

    ReplyDelete
  13. pl post more questions

    ReplyDelete
  14. Very nice collection, great work.

    ReplyDelete
  15. 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.

    ReplyDelete
  16. Nice post . . Very Usefull information

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

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

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

      Delete
  18. 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..

    ReplyDelete
    Replies
    1. could it be possible as you are asking if yes please help us to understand it

      Delete
  19. hello sir!!!!

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

    ReplyDelete
  20. 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

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

    Purnima Das

    ReplyDelete
  22. it is not bad

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

    ReplyDelete

5 recent Java developer posts