Java Interview Questions

Java Interview Questions

Edit Content
Crack Your Interview

Hibernate Interview Questions

Hibernate Interview Questions
Hibernate Interview Questions

1. What is ORM?

ORM stands for Object-Relational mapping. It is a programming paradigm that is used to persist Java objects to database tables.

2. What is Hibernate?

Hibernate is a pure ORM tool that is used to save old java objects to database tables. The main goal of hibernating is to avoid old JDBC code and focus more on business logic. You need to write less code with it.

3. What are the advantages of Hibernate?

Advantages of Hibernate are:

  • Lazy Loading
  • Caching
  • You do not need to maintain the JDBC code, Hibernate takes care of it.
  • You need to write less code
  • It provides a high-level object-oriented API

4. What is the dialect in Hibernate?

Dialect specifies the type of database used in Hibernate so that Hibernate can generate the type of SQL statements.

For example:
Dialect for MySQL database: org.hibernate.dialect.MySQL5Dialect
Dialect for SQL server database: org.hibernate.dialect.SQLServer2005Dialect

5. What are some core interfaces of hibernate?

  • Session
  • SessionFactory
  • Configuration
  • Transaction
  • Query and Criteria interface.

6. Explain briefly the Session interface used in hibernate?

Session the interface is primarily used by hibernate applications. The session is lightweight, short-lived objects which are inexpensive to create and destroy. It allows you to create query objects to retrieve persistent objects. It wraps JDBC connection Factory for Transaction. It holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

7. Are session objects thread-safe?

Session objects are not thread-safe and need to be used in a single thread. Every thread should have its own session object and close it once it is done with the work.

8. Explain briefly the SessionFactory object used in hibernate?

SessionFactory is a heavyweight object and it should be created once per database. SessionFactory object is shared by multiple sessions.

9. What is Configuration class in hibernate?

Configuration class is used to load the required hibernate configuration. It is used to bootstrap hibernate and it is used to locate to hibernate mapping file.

10. Explain briefly about Criteria API in Hibernate?

Criteria API is an API for retrieving entities by composing Criterion objects also referred to as Criterion queries.

Criteria API is an elegant way of building dynamic queries on the persistence database.

Let’s understand with the help of an example.
You have an Employee class with two attributes i.e. name and age.

You want to get a list of employees whose names start with A and their age is greater than 30.

You can write the query as below.

123456 Criteria criteria = session.createCriteria(Employee.class);criteria.add(Restrictions.like(“name”,”A%”);criteria.add(Restrictions.gt(“age”,30);List<Employee> employeeList = criteria.list();
Criteria API

11. Explain briefly the Query interface in Hibernate?

The query interface is an object-oriented representation of Hibernate Query. You can get a query object by calling Session.createQuery() method.

Here is a simple example to execute a Native query using Query APIs.

12345678910 SQLQuery query = session.createSQLQuery(“select name, age from Employee”);List<Object[]> rows = query.list();for(Object[] row : rows){    Employee e = new Employee();    e.setName(row[0].toString());    e.setAge(Integer.parseInt(row[1].toString()));    System.out.println(e);}

12. What are the differences between openSession and getCurrentSession in hibernate?

Parameter openSession get current session
Session object It always creates a new Session object It creates a new Session if not exist, else uses the same session which is in the current hibernate context
Flush and close You need to explicitly flush and close session objects You do not need to flush and close session objects, it will be automatically taken care of by Hibernate internally
Performance In single-threaded environment, It is slower than get current session In single-threaded environment , It is faster than getOpenSession
Configuration You do not need to configure any property to call this method You need to configure the additional property “hibernate.current_session_context_class” to call get the current session method, otherwise it will throw exceptions.
openSession vs getCurrentSession

13. What are the differences between getting and load methods in hibernate?

This is one of the most asked hibernate interview questions.

Parameter get load
Database retrieval It always hits the database It does not hit the database
If null If it does not get the object with id, it returns null If it does get the object with id, it throws ObjectNotFoundException
Proxy It returns a real object It returns a proxy object
Use If you are not sure if an object with an id exists or not, you can use get If you are sure about the existence of an object, you can use the load
differences between getting and load methods in hibernate

14. Can you declare the Entity class as final in hibernate?

Yes, you can declare the entity class as final but it is not considered a good practice because hibernate uses a proxy pattern for lazy initialization, If you declare it as final then hibernate won’t be able to create a subclass and won’t be able to use proxy pattern, so it will limit performance and improvement options.

15. Differentiate between first-level cache and second-level cache?

This is one of the most important hibernate interview questions.

Parameter First level Cache Second-level Cache
Association It is associated at the Session level. It is associated at the SessionFactory level and generally exists one per application.
Default It is enabled by default It is not enabled by default, you need to enable it explicitly
first-level cache vs second-level cache

16. What are the states of objects in hibernation?

Transient: If the object is in a transient state, it means it was never associated with the session and was just created.

Persistent:  If the object is in a persistent state, it means it is associated with the session and you just saved or retrieved the object from the database.

Detached: If the object is in a detached state, it means the session is closed and the object is no more part of the session. If you call merge or update, the object goes back to a persistent state.

17. Does the entity class in hibernate require a no-arg constructor?

Yes, the Entity class in hibernate requires a no-arg constructor because Hibernate uses reflection to create an instance of the entity class and it mandates a no-arg constructor in the Entity class.

18. What is HQL?

HQL stands for Hibernate query language. It is a very simple, efficient, and object-oriented query language that simplifies complex SQL queries. Instead of a table, you use an object to write queries.

19. What are the differences between the save and saveOrUpdate method of session object?

save(): stores object in the database. It generates an identifier for the object and returns it. If the object already exists in the database, it will throw an error.

saveOrUpdate(): SaveOrUpdate method saves the object it identifies does not exist. If it exists, it calls the update method.

20. What are two types of Collections in hibernate?

  • Sorted Collection
  • Ordered Collection

21. What are the differences between sorted and ordered collection in hibernate?

Parameter Sorted Collection Ordered Collection
Sorting The sorted collection uses java’s sorting API to sort the collection. Ordered Collections uses order by clause while retrieval of objects
Default It is enabled by default It is not enabled by default, you need to enable it explicitly
sorted vs ordered collection

22. What is lazy loading in hibernate?

It is used for performance improvement. Lazy loading means when you load parent, child objects won’t get loaded until requested. In fact hibernate loads child objects automatically when you access them. It improves performance as you are not loading the whole object at once.

23. What is LazyInitializationException in Hibernate? Why do you get it?

This exception generally occurs when you use lazy loading and child objects are accessed after the closing session.

That’s all about hibernate interview questions.

24. What are different collection types available in hibernates?

There are 5 collection types available in Hibernate for one to many relationship mappings.

  • Bag
  • Set
  • List
  • Map
  • Array

25. How can you log SQL queries executed by Hibernate?

You can set hibernate.show_sql to true for logging sql queries in Hibernate configuration file.

123 <property name=”hibernate.show_sql”>true</property>
SQL queries

26. Can you share some of the databases supported by Hibernate?

Here are some of the databases supported by Hibernate:

  • MySQL
  • SQLServer
  • PostgreSQL
  • FrontBaase
  • Oracle
  • Sybase SQL Server

27. What inheritance mapping strategies are available in Hibernate?

There are three strategies supported by Hibernate. You can use XML files or JPA annotation to implement them.

  • [Table per Hierarchy](https://java2blog.com/hibernate-inheritancetable-per-class/ “Table per Hierarchy”)
  • [Table per concrete class](https://java2blog.com/hibernate-inheritancetable-per-concrete/ “Table per concrete class”)
  • [Table per subclass](https://java2blog.com/hibernate-inheritancetable-per-subclass/ “Table per subclass”)

28. How to make a class immutable in Hibernate?

You can mark the class as mutable=false and the class will become immutable.

29. What is hibernate configuration file?

Hibernate configuration file contains database configurations such as database URL, username, password, dialect etc and is used to initialize SessionFactory. It also contains mapping files and entity class details.

30. What do you understand by Hibernate tuning?

Hibernate tuning is the process of optimizing the performance of Hibernate application.

Some of the performance tuning strategies are:

  • Data Caching
  • Session management
  • SQL optimization