Hibernate Interview Questions and Answers


What is Hibernate?



Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users <span class="ilad">to develop</span> persistent classes following object-oriented principles such as association, inheritance, polymorphism, <span class="ilad">composition</span>, and collections.


What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java <span class="ilad">application</span> in to the tables of a relational database using the metadata that
describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

Why hibernate is advantageous over Entity Beans and JDBC?

An entity bean always works under the EJB container, which allows reusing of the object external to the container. An object can not be detached in entity beans and in hibernate detached objects are supported.<br />Hibernate is not database dependent where as JDBC is database dependent. Query tuning is not needed for hibernate as JDBC is needed. Data can be placed in multiple cache which is supported by
hibernate, whereas in JDBC the cache is to be implemented.&nbsp;


What are the different levels of ORM quality?

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. <br />
<br />
" 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. <br />
<br />
" 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.


What are derived properties?

The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.


Define HibernateTemplate?

<i>org.springframework.orm.hibernate.HibernateTemplate</i> is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.


What are the benefits does HibernateTemplate provide?


HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.


How will you configure Hibernate?

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.


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 thangetId() 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 saveOrUpdatefor 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.



What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one.

  • Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
  • SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
  • Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
  • Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
  • Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

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.



What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.



What are the Extension interfaces that are there in hibernate?

There are many extension interfaces provided by hibernate.

  • ProxyFactory interface – used to create proxies
  • ConnectionProvider interface – used for JDBC connection management
  • TransactionFactory interface – Used for transaction management
  • Transaction interface – Used for transaction management
  • TransactionManagementLookup interface – Used in transaction management.
  • Cahce interface – provides caching techniques and strategies
  • CacheProvider interface – same as Cache interface
  • ClassPersister interface – provides ORM strategies
  • IdentifierGenerator interface – used for primary key generation
  • Dialect abstract class – provides SQL support


What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs.
  1. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.
  2. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.



What is meant by Method chaining?

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.


1SessionFactory sessions = new Configuration()
2 .addResource("myinstance/MyConfig.hbm.xml")
3  .setProperties( System.getProperties() )
4 .buildSessionFactory();



What is HQL?

HQL stands for Hibernate Query Language. Hibernate 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.


What are the different methods of identifying an object?

  • There are three methods by which an object can be identified.
  • Object identity – Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.
  • Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity.
  • Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

What are the different approaches to represent an inheritance hierarchy?
  • Table per concrete class.
  • Table per class hierarchy.
  • Table per subclass.

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.


Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?


How do you invoke Stored Procedures?

{ ? = call selectAllEmployees() }


Explain Criteria API ?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();


What are the benefits does HibernateTemplate provide?


org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
The benefits of HibernateTemplate are :
HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.

If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows:
set show_sql property to true in configuration file.


How can Hibernate be configured to access an instance variable directly and not through a setter method ?


By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

How can a whole class be mapped as immutable?

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.

What are the types of Hibernate instance states ?

Three types of instance states:

  • Transient -The instance is not associated with any persistence context.
  • Persistent -The instance is associated with a persistence context. You can update object in database by using session.flush() method.
  • Detached -The instance was associated with a persistence context which has been closed – currently not associated. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session.

What is automatic dirty checking?

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.



How to implement Optimistic locking in Database?


You can implement optimistic locks in your DB table in this way (This is how optimistic locking is done in Hibernate):
- Add integer "version" column to your table.
- Increase value of this column with each update of corresponding row.
- To obtain lock, just read "version" value of row.
- Add "version = obtained_version" condition to where clause of your update statement.
- Verify number of affected rows after update. If no rows were affected - someone has already modified your entry.

Your update should look like
UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2;


What is Second level Cache and QueryCache in Hibernate?

Second level Cache is maintained at SessionFactory level and It improves 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.

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.

{ 15 comments... read them below or Comment }

  1. Hibernate and spring are the frameworks of Java. A java developer should be well aware of these frameworks in order to master the technology and work efficeiently.
    spring training in chennai | hibernate training in chennai
    FITA Academy reviews

    ReplyDelete
  2. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    python training in rajajinagar
    Python training in btm
    Python training in usa
    Python training in marathahalli

    ReplyDelete
  3. Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 
    java course in chennai | java course in bangalore


    java course in tambaram | java course in velachery

    ReplyDelete
  4. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    ReplyDelete
  5. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Training in Bangalore | Amazon Web Services Training in bangalore , india

    AWS Training in pune | Amazon Web Services Training in Pune, india

    ReplyDelete
  6. I would like to share the informative contents with my office circle...Really the contents of the blogs are creating a good opportunities...Keep posting
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  7. this is very informative blog to explore many things
    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  8. Myself so glad to establish your blog entry since it's actually quite instructive. If it's not too much trouble continue composing this sort of web journals and I normally visit this blog. Examine my administrations.  
    Read these Salesforce Admin Certification Topics which are really helpful. I read these Salesforce Admin and Developer Certification Dumps and very much useful for me. I recommend this Salesforce Developer Training and Certification Course for you.  

    ReplyDelete
  9. Its really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.
    Java Training in Chennai

    Java Training in Velachery

    Java Training in Tambaram

    Java Training in Porur

    Java Training in OMR

    Java Training in Annanagar


    ReplyDelete

About This Site

Howdy! My name is Suersh Rohan and I am the developer and maintainer of this blog. It mainly consists of my thoughts and opinions on the technologies I learn,use and develop with.

Blog Archive

Powered by Blogger.

- Copyright © My Code Snapshots -Metrominimalist- Powered by Blogger - Designed by Suresh Rohan -