Hibernate Interview Questions


Question 1:

What is ORM?

Often we need to persist/store our application data. For example:- Registration data for further login, oder information etc. For this, most often we use database to store the data. These databases like Oracle, DB2 are relational database whereas programming language like C#, Java are object oriented. 

Object-Relational Mapping (ORM) is a technique that lets you query, manipulate and access data from database using an object oriented paradigm. This is done by mapping of database tables to domain object classes.

For example:

User

Id Name Age

The above User table will be represented as domain object class as shown below:

class User{
int id;
int age;
String name;
   public void setId( int id ) {
      this.id = id;
   }
   public int getId() {
      return id;;
   }
   public String getName() {
      return name;
   }
   public void setFirstName( String name ) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge( int age ) {
      this.age = age;
   }
}

All the operations like update, create to User table will be done through User entity class in application.

Question 2:

Explain hibernate architecture?

The below diagram shows a high-level view of Hibernate architecture.

Hibernate Architecture

Hibernate archirtecture has following components:

Configuration: The org.hibernate.cfg.Configuration object reads the configuration files to connect database. SessionFactory object is creaated used Configuration object.

SessionFactory: The SessionFactory is thread-safe as it is created one per database and can be concurrently accessed by multiple threads and is created at the time of application startup. It is created using Configuration object. It is used to create session object.

Session: The org.hibernate.Session is used to create object that are used to communicate between application and persistent store(database). This is factory for org.hibernate.Transaction. As it is not thread-safe, application should create and destroy it once a unit of work done though it may be used to multiple units as per requirement. 

Transaction: The org.hibernate.Transaction is used to represent unit of work. A transaction is associated with a session and is usually instiantiated by a call to Session.beginTransaction()

Query: The org.hibernate.Query is an object oriented representation of Hibernate query. A query instance is obtained by calling session.createQuery(). A query object is used to bind query parameters like number of results fetched etc.

Criteria: The org.hibernate.Criteria is used to retrieve entities by composing some criteria like getting all users by specific age or specific weight etc. The Session is factory for Criteria.

Question 3:

What are the key benifits of Hibernate?
OR,
What are the advantages of Hibernate over JDBC?

Rather we start with advantages of Hibernate, let us discuss about disadvantage of traditional JDBC to communicate with database/persistence store.

  1. In JDBC you have to write huge queries which not only requires understanding of SQL syntax but also make code redundant throughout the application. What if any framework which can result in no sql query code in application and provides in-built methods to interact with database. The answer is ORM.
  2. If you write sql-queries in application and imagine in future if you want to change your database, it will require to change your SQL queries and code. Hibernate is database independent. Hibernate abstracts our application away from SQL queries. If you want to switch to other SQL database it requires few changes in hibernate configuration files rather change in code.
  3. If you want caching, in JDBC you need to implement it, whereas hibernate supports two level of caching. 
Question 4:

What is hibernate session and session factory?

SessionFactory: The SessionFactory is used to configure hibernate for the application and is thread-safe as it is created one per database and can be concurrently accessed by multiple threads and is created at the time of application startup. It is created using Configuration object. It is used to create session object.

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

Session: The org.hibernate.Session is used to create object that are used to communicate between application and persistent store(database). This is factory fororg.hibernate.Transaction. As it is not thread-safe, application should create and destroy it once a unit of work done though it may be used to multiple units as per requirement. 

Session session = sessionFactory.getCurrentSession();

Question 5:

How do you configure session factory in spring configuration file?

You can configure hibernate using applicationContext.xml  where you can define datasource  and add SessionFactory bean and finally add TransactionManagerBean.

 


Question 6:

What type of transaction management is supported in Hibernate?

Hibernate can be used in managed(For eg. inside Spring container) as well as unmanaged environments(for eg. Swing Application). Hence, it supports following transactions 

  1. Non Managed Transactions: JDBC
  2. Managed Applications: JTA
Question 7:

What is lazy loading and how do you implement it in hibernate?

Let us take an example of Books section of Modernpathshala website. It comprises of various categories under which there may exists 1000's of books. So the relation will be One to many between Category and Book Table. So while fetching Category either we can get books associated with it. This approach will not only take huge amount of memory but also degrade the performance of the system. To manage this problem, Hibernate provides a facility called lazy loading. When enabled, an entity’s associated entities will be loaded only when they are directly requested.

To enable lazy loading explicitly you must use "fetch = FetchType.LAZY" on a association which you want to lazy load when you are using hibernate annotations as shown in below example:

@OneToMany( mappedBy ="category", fetch = FetchType.LAZY )
private List<Book> bookList;
Question 8:

What is the difference between hibernate get and load methods?

The key difference between load and get method in Hibernate is:

  1. Call to database: Get method always query to database whereas load method may return reference of an object from database or cache.
  2. Return: Load method will always return a proxy object with the given id, irrespective of id exist in database or not. If you try to access the properties of the object and if it does not exists in database, it will return ObjectNotFoundException whereas get method returns null if object is not found in database.
Question 9:

What is the use of session.flush() in Hibernate?

session.flush() method forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). But it does not means that the transaction has been committed. To commit the transaction you should explicitly call commit() method. 

You can synchronize your database with small chunks of data using flush() instead of committing a large data at once using commit() and face the risk of getting an Out Of Memory Exception.

For example:-

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 30 == 0 ) {  //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();
Question 10:

How do you configure 2nd level cach in hibernate?

To configure second level cache in hibernate, you should add following configurations as listed below:

  1. Add provider class in your hibernate configuration file i.e hibernate.cfg.xml
    <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
    <property name="hibernate.cache.use_second_level_cache">true</property>  
  2. Now configure cache usage setting in hbm.xml file
    <class name="com.modernpathshala.entity.Category" table="CATEGORY">
        <cache usage="read-write"/>
    </class>
    Alternatively if you are using annotations you can do this as
    @Entity
    @Table(name = "CATEGORY")
    @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="category")
    public class Category{
    ...
    }
  3. Create xml file called ehcache.xml and store in at classpath location
Share interview questions

Comments

Comments
comments powered by Disqus

Navigation

Social Media