Hibernate interview questions and answers

What is ORM?

ORM refers to the Object-Relational Mapping. It is a programming technique for converting data between incompatible type systems like relational databases and object oriented programming languages like java.
See more at: ORM overview.

What is hibernate?

Hibernate framework is an object-relational mapping library for the Java language. It is an open source persistent framework started by Gavin King in 2001. It provides the facility to map the java classes to relational database tables and Java data types to SQL data types.
Note: Hibernate framework is act as an intermediate layer between java objects and relational database.
See more at: Hibernate framework.

Explain hibernate architecture?

Hibernate architecture consist of hibernate core components and use existing Java APIs. It uses JDBC API for common functionality to communicate with relational database and JNDI and JTA to integrate hibernate to the java application servers.

What are the core components are of hibernate architecture?

• Configuration
• SessionFactory
• Session
• Query
• Criteria
• Transaction

What is hibernate configuration file?

Hibernate works as an intermediate layer between java application and relational database. So hibernate needs some configuration setting related to the database and other parameters like mapping files. A hibernate configuration file contains all such information.

What is hibernate mapping file?

Hibernate mapping file is used by hibernate framework to get the information about the mapping of a POJO class and a database table.
It mainly contains the following mapping information:
1. Mapping information of a POJO class name to a database table name.
2. Mapping information of POJO class properties to database table columns.

What is SessionFactory?

The SessionFactory object is created from the Configuration object. It is thread-safe object and used by all threads of the application. It is act as a factory for session objects and client for ConnectionProvider. It maintains the second level cache of the data.

Is SessionFactory a thread-safe object?

Yes.

What is Session?

The session object is created from the SessionFactory object. It is act as a factory for Transaction, Query and Criteria. Session objects are not thread-safe. It maintains the first level cache.

Is Session a thread-safe object?

No.

Explain Object states in Hibernate.

A persistent class object can be in one of the following three states:
1. Transient.
2. Persistent.
3. Detached.

Explain transaction management in hibernate.

Transaction: 
A transaction is a sequence of operation which works as an atomic unit. A transaction only completes if all the operations completed successfully. A transaction has the Atomicity, Consistency, Isolation and Durability properties (ACID).
Transaction interface:
Transaction interface provides the facility to define the units of work or transactions. A transaction is associated with a session. We have to call beginTransaction()method of Session to start a transaction (Session.beginTransaction()).

What is difference between openSession and getCurrentSession?

The SessionFactory.getCurrentSession() returns a session bound to a context. We don’t need to close this. We have to set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session. We can access that session anywhere else by using the SessionFactory.getCurrentSession(). thread
The SessionFactory.openSession() always opens a new session that we have to flush() and close() once we are done with the operations.

What is difference between Hibernate Session get() and load() method?

session.load()
• It will always return a “proxy” in Hibernate terms without hitting the database. In Hibernate, proxy represents a fake object with the given identifier value but its properties are not initialized yet.
• If no record found, it will throws an ObjectNotFoundException.
• Example: Let we call session.load(Employee.class,new Integer(10)). Hibernate will create one fake Employee object [row] in the memory with id 10, but other properties of Employee class will not even be initialized. When we try to retrieve other properties of Employee object, it will hit the database and search the record with employee id 10 and fetch the values. It will throws ObjectNotFoundException in case when no record found.
session.get()
• It always hit the database and return the real object, an object that represent the database record not proxy.
• It return null if no record found.
• It will not throw any exception in case when no record found.

What is the difference between session save and session persist method in hibernate?

Save():

1. Syntax: public Serializable save(Object object) throws HibernateException.
2. The return type of the save method is java.io.Serializable. It returns the generated Id after saving the record.
3. It can save the changes to the database outside of the transaction. i.e. Save method can be used inside or outside the transaction.
4. Session.save() for a detached object will create a new row in the table.
5. Save method takes more time to execute.

Persist():

1. Syntax: public void persist(Object object) throws HibernateException.
2. It does not returns generated Id after saving. Its return type is void.
3. Persist method can be used only within the transaction.
4. session.persist() for a detached object will throw PersistentObjectException as it is not allowed.
5. Persist method takes less time to execute.

What is the difference between session.save session.saveorupdate and session.persist in hibernate?

Save:

Save
Serializable save(Object object) throws HibernateException
 
Serializable save(String entityName,
Object object)
throws HibernateException
Save method is used to store an object into the database. It insert an entry if the identifier doesn’t exist. It will throw error if the identifier already exist.

Update

void update(Object object) throws HibernateException
 
void update(String entityName,
Object object)
throws HibernateException
Update method in the hibernate is used for updating the object using identifier. It will throw an exception if the identifier is missing or doesn’t exist.

saveOrUpdate

void saveOrUpdate(Object object)throws HibernateException
 
void saveOrUpdate(String entityName,
Object object)
throws HibernateException
The saveOrUpdate method calls save() or update() method based on the operation. If the identifier exists, it will call update method else the save method will be called.

What is the difference between session.merge vs session.update in hibernate?

Update and Merge both work on detached instances, ie instances which have a corresponding entry in the database but which are currently not attached to a Session. Both methods are used to convert these object into persistence state from detached state.
The update tries to reattach the instance, that means that there may be no other instance of the persistent entity attached to the Session right now otherwise an exception is thrown. i.e. update method cannot be used when the same object exists in the session.
The merge copies all values to a persistent instance in the session. The input object is not changed. So merge is more general than update, but may use more resources. i.e. The merge method will work fine when the same object exists in the session.

Example:

Employee currentEmp = (Employee)session.get(Employee.class, 10);
System.out.println("Before merge: " + currentEmp.getName());
Employee changedEmp = new Employee();
changedEmp.setId(10);
changedEmp.setName("New Name");
//session.update(changedEmp); // Throws NonUniqueObjectException
session.merge(changedEmp);
System.out.println("After merge: " + current.getName());

Explanation:

In the above example we have loaded an Employee object of id ‘10’. After that we have created a new Employee object ‘changedEmp’ with same ID ‘10’. Now if we try to call update method on this ‘changedEmp’ object, then Hibernate will through a NonUniqueObjectException, because the same object (Employee) with Id ‘10’ already exists in session.
But merge() method will work fine and the name will get changed and saved into the database. After this on printing the current object, it will print the latest changed value, since when the merge occurs the value loaded in session gets changed.

What will happen if we don’t have no-args constructor in Entity bean?

Hibernate uses Reflection API to create instance of Entity beans. The method Class.newInstance() is used for creating the instance of Entity beans which requires no-args constructor. So if we won’t have no-args constructor in entity beans, hibernate will fail to instantiate it and we will get HibernateException.

Can we make an hibernate entity class final?

Yes, we can make a Hibernate Entity class final, but that’s not a good practice. Since, hibernate use proxy classes for lazy loading of data which is done by extending the entity bean. If the entity bean will be final then lazy loading will not be possible which results into low performance.

What is HQL?

HQL stands for Hibernate Query Language. HQL syntax is quite similar to SQL syntax but it performs operations on objects and properties of persistent classes instead of tables and columns. Hibernate framework translate HQL queries into database specific queries to perform action.

What is HCQL?

HCQL stands for Hibernate Criteria Query Language. As we discussed HQL provides a way of manipulating data using objects instead of database tables. Hibernate also provides more object oriented alternative ways of HQL. Hibernate Criteria API provides one of these alternatives. HCQL is mainly used in search operations and works on filtration rules and logical conditions.

Explain Named queries.

Named query is a concept of using queries by name. First a query is defined and a name is assigned to it. Then it can be used anywhere by this alias name.
Syntax of hibernate named query using xml.
<query name="queryName">
<![CDATA[queryString]]>
</query>

Explain hibernate collections mappings.

Collection is a group of objects. As hibernate maps the entity classes to the database tables so if an entity has a collection of values for a property then these types of properties can be mapped to the any one of the available java collection interfaces.

Explain hibernate association mappings.

Association: 
Association between two or more things is refers to the state of being associated i.e. how the things are related to each other.
Association in hibernate tells the relationship between the objects of POJO classes i.e. how the entities are related to each other. Association or entities relationship can be unidirectional or bidirectional.

Explain hibernate component mapping.

Component Class: 
A class is said to be a component class if it is completely depends upon its container class life cycle and it is stored as a member variable not as an instance.
Component mapping:
If an entity class has a reference entity as a component variable then this property can mapped by using element.

How to log hibernate generated sql queries in log files?

We have to set hibernate.show_sql property in hibernate configuration.
<property name="hibernate.show_sql">true</property>

No comments: