StuffArrow is under maintenance. These are the demo deals and offers you are seeing here. We will come up with fresh and live deals and offers soon. Thanks for your patience. Keep visit our site for updates

Hibernate Interview Question and Answers

Hibernate Interview Questions and Answers

Hibernate is very popular these days, as this is consider as one of the best ORM  in java. it is one of the hot topic in java interview. So here we will publish Hibernate interview question and Answers, which can be asked in Interview.

  1. what is Persistence in Java?
  2. what is Detached state of object in java
  3. What is ORM and its benefits?
  4. Why we use Dialect in Hibernate? what is the purpose of it?
  5. what is dirty read?
  6. what is the purpose of session factory? how sessions are created in hibernate.
  7. what is first level cache in hibernate
  8. what is second level cache in hibernate
  9. what is hibernate configuration file?
  10. What is difference between get() and load()?
  11. what can be the different states of the object in hibernate.
  12. what is difference between save or saveOrUpdtae in hibernate?
  13. what is HQL in hibernate?
  14. what is native query in Hibernate?
  15. what is named query in hibernate?
  16. What is hibernate Template class?
  17. what is the purpose of Transaction Factory in Hibernate?
  18. what are the various properties used in configuration file?
  19. what is criteria in hibernate, why we use it?
  20. Is SessionFactory is thread safe?
  21. what is difference between save() and persist()?
  22. what is the difference between Merge and update()?
  23. How many types of mapping in hibernate?
  24. what is lazy loading?
  25. what is eager loading in hibernate?
  26. what is differenc between first level cache and Second Level Cache?
  27. what are various generator classes in hibernate?
  28. How to create sequence in table in hibernate?
  29. what is cascade? different types of cascades?
  30. how to call stored procedure in Hibernate?
  31. what is the purpose of “show_sql”property in configuration file?
  32. what are various collection types in hibernate?
  33. what is the purpose of callback interfaces in hibernate.
  34. What is batch processing in hibernate?
  35. Is session a thread-safe in hibernate?
  36. How many types of mappings are possible in hibernate?
  37. What is transaction management in hibernate?

 

What is Persistence?

Persistence is state of the object, when some object is in session scope and if any changes are made with that object then that changes will saved in Database. It means that object is directly sync with db.

 

What is detached state of object?

Detached state means that java object is not associated to any session.

 

What is ORM? What are its benefits

ORM is Object-Relation-Mapping, it provides a platform where java POJO class can directly map to database. In ORM, a class is mapped to DB table. Class attributes are mapped to table columns.

The benefits of ORM approach is that we need not write extra code of mapping the object to persist with DB.

 

Why we use dialect in hibernate? What is the purpose of dialect? Where dialect is present?

Dialect helps you to switch between the DBs in application. e.g. in application earlier you were using MySQL DB, but now you have to use Oracle or some other Db then you need to change just dialect name and you need not to change whole code for this.

Dialect property is present in configuration file.

 

What is dirty read in java?

Dirty read is process or incident when one transaction is reading the data while other transaction is updating the same date but not yet committed that changes.

 

What is the purpose of Session factory? how sessions are created in hibernate.

Session factory: Session factory is used to create the sessions for hibernate.  Usually an application has one session Factory. Session factory is configured in hibernate configuration file(hibernate.cfg.xml).

 

Snippet of Session factory from Configuration file:

<session-factory>
    <!-- SQL Dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Database Connection Settings -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/StuffArrowDB</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>

    <!-- Echo All Executed SQL To Console -->
    <property name="show_sql">true</property>

    <!-- Specifying Session Context -->
    <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>

    <!-- Mapping With Model Class Containing Annotations -->
    <mapping class="com.jcg.hibernate.id.StuffArrow" />
  </session-factory>

 

Snippet to create session in Java class

//creating configuration file object  
    Configuration config=new Configuration();  
    config.configure("hibernate.cfg.xml");//path of configuration file  
      
    //creating session factory object  
    SessionFactory factory=config.buildSessionFactory();  
      
    //creating session object  
    Session session=factory.openSession();  
      
    //creating transaction object  
    Transaction t=session.beginTransaction();  

 

What is first level cache in hibernate?

First level cache associated with session object in hibernate. First level cache is by default in hibernate. One more thing that object cache associated with one session is not visible to other session object cache.

 

What is second level cache in hibernate?

Second level cache in hibernate is associated with Session factory. In this session cache is associated with other session cache. By default, it is not set. We have to explicitly set the second level cache in hibernate.

 

What is hibernate configuration file?

Hibernate.cfg.xml is hibernate configuration file. This is very important file, as it is related to configuration. Session factory, DB mappings of classes and other configurations are mentioned in this file.

 

What is mapping file in hibernate?

As we know hibernate is ORM. So mapping files refer here to make the mapping of POJO class to DB table.

 

Snippet from mapping file

<hibernate-mapping>
   <class name = "Employee" table = "EMPLOYEE">
      
      <meta attribute = "class-description">
         This class contains the employee detail. 
      </meta>
      
      <id name = "id" type = "int" column = "id">
         <generator class="native"/>
      </id>
      
      <property name = "firstName" column = "first_name" type = "string"/>
      <property name = "lastName" column = "last_name" type = "string"/>
      <property name = "salary" column = "salary" type = "int"/>
      
   </class>
</hibernate-mapping>

Here Employee is POJO class which is mapped to DB table EMPLOYEE.

 

What can be the different states of the object in hibernate?

In Hibernate object can have 3 states: Transient,Persist and detached

Transient : In this state object does not associated with any session. it is newly created object prior to bound any session

Persist : In this state, Object is associated with session and any changes with leads to database for this object.

Detached : in detached state, object is removed to from hibernate session and it does not connected to database anymore.

 

public class PersonObj {
    public static void main(String[] args) {
 
        // Transient object state
        Person person = new Person();
        person.setId(1);
        person.setName("Raj");
        // Transient object state
        Session session = new AnnotationConfiguration().configure()
                .buildSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        // Persistent object state
        session.save(person);
        t.commit();
        // Persistent object state
        session.close();
        // Detached object state
 
    }
}

 

What is difference between save or saveOrUpdate in hibernate?

Save: save method in hibernate will save the object in hibernate or we can say it will persist the object and it will return the id corresponding to that.

saveOrUpdate :  saveOrUpdate will first see in the database, it object is not present in db then it will save the object otherwise if object is already present in db it will update the object in db. it means saveOrUpdate can perform two operations save and update.

 

What is HQL in hibernate?

HQL is Hibernate Query Language, used in hibernate. HQL is similar to SQL. it is different from SQL in a way that SQL operates on database columns or fields directly where as HQL operates on the java object and its properties.

 

What is native SQL query in Hibernate?

Hibernate provides the option to use SQL queries directly into hibernate. e.g. we can use session.createSQLQuery(String query) to create query and use it.

In below code snippet , we are using SQL native query  in hibernate

session.createSQLQuery(“select stud_id, stud_name from Student”);

// Get All students
Transaction tx = session.beginTransaction();
SQLQuery query = session.createSQLQuery("select stud_id, stud_name from Student");
List<Object[]> students= query.list();

 

What is named query in hibernate?

In hibernate we can provide the name to particular query and can used in multiple files. its called named query where particular name is assigned to the query and when we need to fire that query we get it from its name.

There are two ways to defined named queries:

  • By mapping file
  • By annotation

 

What is the purpose of Transaction Factory in Hibernate?

Transaction in hibernate is the unit of work done. it is usually associated with session.below are the few methods of transaction.

Transaction tx = session.beginTransaction();

tx.commit();

tx.rollback();

 

What are the various properties used in configuration file?

Hibernate configuration file has following few important properties:

hibernate.dialect : This is related to database used in hibernate application. different db has different dialect.

hibernate.connection.url :This is related to Database URL

hibernate.connection.username: This is related to Database username

hibernate.connection.password: This is related to Database password

hibernate.connection.driver_class: This is related to Database driver class

hibernate.show_sql : This is used to show the sql statements on console.

 

What is criteria in hibernate, why we use it?

Criteria is the query concept in hibernate. Criteria is also used fetch the result from the database, but it is used only in select operations. it can not be used in non-select operation.

As from the name Criteria, it fetch the result based on some criteria. e.g. if we have to fetch all the employees whose salary is less than 25000, then we can use criteria to perform the operations. below is the code snippet to use criteria in hibernate.

Criteria cr = session.createCriteria(Emp.class);
cr.add(Restrictions.eq("salary", 25000));
List results = cr.list();

 

we can perform multiple operation like greater than, equal to, like,between etc with criteria.

 

Is SessionFactory is thread safe?

Yes SessionFactory is thread safe. multiple threads can use session factory simultaneously.

 

What is difference between save() and persist()?

Both save and persist are used to save the object in java. but there are few differences:

  • persist is used by JPA where as save is used by hibernate only.
  • persist method return void where as save return the serialize object.
  • persist method can not be called outside the transaction boundary, but save method is called outside the transaction boundary.
  • persist does not guarantee that identifier value will be assigned imediately to the persistence instance, it might assigned at flush time. where as save method returns the identifier immediately.

  What is difference between get() and load()?

  Session.load() –

  • This will always return the proxy object, without hitting the database.
  • It will throw exception(ObjectNotFoundException), if object is not found

  Session.get():

  • It will always hit the database.
  • It will return null, if object is not found in database.

What is the difference between Merge and update()?

Merge and update both are used in session scope in hibernate to update the changes in database.

Update: update is used when object is load and in session cache. if session is flushed or closed and then we try to update the object, it will throw exception.

Merge: merge can be used anytime whether object is in session cache or not.you can prefer to use merge, if you want to save the changes without knowing the session state.

 

What is lazy loading in hibernate?

Lazy loading is concept where we don’t load the whole object initially. Let’s understand this by taking example.

Suppose you have an online store, and each product has its own unique properties and other things like quantities, availability of product etc.

When some user come on online store and request for products catalog, at that time we only show all products name, rather than other options like

  • whether that products are available at that moment or not.
  • Different colors are present or not. Etc.

It is called lazy loading when we don’t initialize the whole object. As we don’t know which product the user is going to purchase, so we save our memory and fetching time.

So, Lazy Loading helps to increase the performance as we don’t load the whole object.

 

What is eager loading in hibernate?

Eager loading is the process where we load the whole object. It is reverse the lazy loading.

In the starting we initialize the whole object. It impacts on performance.

As we discussed above example of online store, in eager loading we will fetch all the properties of all the object during product catalog request by user.

 

What is difference between the first level cache and second level cache?

First level cache is associated with session object. First level cache is available by default. If session is flushed or closed, then cache associated with the object will be vanished. One session cache cannot be shared in other session cache.

Second Level Cache is associated with session factory. It is not available by default. If we enable the second level cache, then session cache can be used with other sessions.

e.g. let’s take an example to understand the both

we have a student class and we have to load student say id=1 in session. And later we close/flush that session. Suppose later point of time, we did some information from this object.

Now if we are using first level cache, then we have to create another session to hit the DB and fetch the object.

But in case of second level cache, we van directly get the information from session factory. So In Second level cache, we don’t need to hit the DB again and again.

 

What are various generator classes in hibernate

Generator classes are used to create unique value or primary key value. Hibernate provides some default or built-in generators as below:

 

  • Increment
  • assigned
  • hilo
  • native
  • identity
  • seqhilo
  • uuid
  • guid
  • select
  • sequence
  • foreign

 

What is cascading in hibernate? Types of Cascading in hibernate?

Cascading is the concept used in mappings like many to many, one to many etc. cascading means whether the dependent object will be insert/delete/update.

e.g. let’s understand cascading with example.

If employee has multiple phone no. and we have to perform insert/delete/update operations on the employee and its phone no. then cascade came into picture.

When there is relation of parent-child and we have to transfer changes of parent to child, then we can use cascade.

 

Types of cascade:

CascadeType.PERSIST: all the entities held in this filed will persist.

CascadeType.ALL : This means when operation like insert/delete/update will happened, all the fields will reflected accordingly.

CascadeType.REMOVE: this means when we will delete the entity, all the fields held by this entity will be deleted.

CascadeType.REFRESH : this means when we will refresh the entity, all the fields held by this entity will be refreshed.

 

How to call stored procedure in hibernate?

In normal java we call stored procedure by using callable statement

Call storedProcedureName();

 

But in hibernate we have to append some code to call it.

There are three ways to call the stored procedure in hibernate:

  1. createSqlQuery() : we can use createSqlQuery to call the stored procedure
Query query = session.createSQLQuery(
  "CALL getEmpDetails(:empId)")
  .addEntity(Emp.class)
  .setParameter("empId ", "101");

In this query, we can append the stored procedure name inside createSqlQuery and add class and parameter accordingly.

2. Using XML mapping: we can call stored procedure in xml mapping file also. We can put this query into xml mapping file.

<sql-query name=" callGetEmpDetails ">
  <return alias="emp" class="com.stuffArrow.Employee"/>
  <![CDATA[CALL getEmpDetails (:empId)]]>
    </sql-query>

3.We can also create named query to call Stored procedure.

@NamedNativeQueries({
  @NamedNativeQuery(
  name = " callGetEmpDetails",
  query = " CALL getEmpDetails(:empId)",
  resultClass = Emp.class	
)

 

What is the purpose of “show_sql” property in configuration file?

“Show_sql” property will show the sql statement executing in console. You can put this property in hibernate.cfg.xml file.if it is set to true, it will show the SQL statements in the console, else not.

<!--hibernate.cfg.xml -->
<property name="show_sql">true</property>

 

There is one another property “format_sql”, if it is set to be true, then it will format the SQL query as well.

<!--hibernate.cfg.xml -->
<property name="use_sql_comments">true</property>

 

What are the various Collection types in hibernate?

Bag, set, map, list, array are various collection types in hibernate.

 

What is the purpose of callable statement in hibernate?

Callable statements are used to execute the stored procedure in hibernate.

 

What is batch processing in hibernate?

Batch processing means to process the data in batch. In hibernate configuration file following property we use to process the records in batch. Batch processing can be done by using this property in hibernate.cfg.xml file.

 

<property name = "hibernate.jdbc.batch_size">50 </property>

Batch processing is very helpful, if we are doing CRUD operations on very large data. It will quickly process the data in batch say 50 as per above property. Value can be anything.

e.g. if you have to insert say I million (1000,000) records in one go, then it will mandatory to use batch processing while inserting, otherwise OutOfMemoryException can occur.

 

Is session a thread-safe in hibernate?

No, session is not thread safe, multiple thread can share the same session.

 

How many types of mappings are possible in hibernate?

In hibernate, there are 4 types of mappings:

  • One to one mapping
  • One to many mapping
  • Many to one mapping
  • Many to many mapping

 

What is transaction management in hibernate?

Transaction Management help the session to complete the database operation. In Hibernate we start the transaction with session.beginTransaction().

Session need the transaction to deal with database operations.

 

 

Newsletter

%d bloggers like this: