Top 30 Interview Questions And Answers On Hibernate Java

  • By Shital Chauhan
  • December 14, 2024
  • JAVA Programming
Top 30 Interview Questions And Answers On Hibernate Java

Top 30 Interview Questions And Answers On Hibernate Java

Top 30 Interview Questions and Answers on Hibernate Java: Prepare with essential Hibernate concepts, key questions, and expert answers for your next Java interview.

 

Q1. What is hibernate?

Ans: Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate, and retrieve data from the database.

 

Q2. What is ORM?

Ans: ORM is an acronym for Object/Relational mapping. It is a programming strategy to map objects with the data stored in the database. It simplifies data creation, data manipulation, and data access.

 

Q3. Explain hibernate architecture.

Ans: Hibernate architecture comprises of many interfaces such as Configuration, SessionFactory, Session, Transaction, etc.

Explain hibernate architecture

 

Q4. What are the core interfaces of Hibernate?

Ans: The core interfaces of the Hibernate framework are:

Configuration: Used to configure the database properties and external resources to hibernate

Session Factory: It’s also called the second level cache, and it is used to generate the instance of Session. Its scope is application level.

Session: It actually holds the connection object required to connect with the database. It’s also known as the level cache used to persist the object.

Query: Its API is used to execute and customize the queries, it supports both HQL (Hibernate Criteria Query Language) and Native SQL.

Criteria: Provided a programmatic way to create queries based on entity attributes.

Transaction: It’s used to manage the transaction with hibernate, and represents a unit of work that can be committed or rolled back.

 

Q5. Mention some of the advantages of using ORM over JDBC.

Ans: ORM has the following advantages over JDBC:

  1. Application development is fast.
  2. Management of transactions.
  3. Generates key automatically.
  4. Details of SQL queries are hidden.

 

Q6. Define criteria in terms of Hibernate.

Ans: The objects of criteria are used for the creation and execution of the object-oriented criteria queries.

 

Q7. List some of the databases supported by Hibernate.

Ans: Some of the databases supported by Hibernate are:

DB2, MySQL, Oracle, Sybase SQL Server, Informix Dynamic Server, HSQL, PostgreSQL, FrontBase

 

Q8. What is an ORM? How does Hibernate implement it?

Ans: ORM (Object-Relational Mapping) is a technique to map object-oriented entities with relational databases. Hibernate implements ORM using annotations, XML, and HQL.

 

Q9. How is SQL query different than HQL created in Hibernate?

Ans: SQL queries work on database columns and table names HQL queries are object-oriented they work on pojo class and its attributes.

 

Q10. What is a Hibernate configuration file?

Ans: The configuration file (hibernate.cfg.xml) contains database connection settings, Hibernate properties, and mapping details.

 

Q11. Explain the role of the Session and SessionFactory in Hibernate.

Ans: SessionFactory is a heavyweight object used to create Session instances, which helps to persist and retrieval of entities.

 

Q12. What is the use of @Id annotation?

Ans: It’s used to create primary key column in a relational database with hibernate.

 

Q13. How can we add criteria to a SQL query?

Ans: A criterion is added to a SQL query by using the Session.createCriteria() method

 

Q14.Define persistent classes.

Ans: Classes whose objects are stored in a database table are called persistent classes.

 

Q15. What is the use of the Hibernate dialect property

Ans: The hibernate dialect property defines the type of database used to generate the queries.

 

For Free, Demo classes Call: 020-71173125

Registration Link: Java Training in Pune!

 

Q16. Is SessionFactory a thread-safe object?

Ans: Yes, SessionFactory is a thread-safe object, many threads cannot access it simultaneously.

 

Q17.What is a Session?

Ans: It maintains a connection between the hibernate application and the database. It provides methods to store, update, delete, or fetch data from the database such as persist(), update(), delete(), load(), get() etc.

It is a factory of Query, Criteria, and Transaction i.e. it provides factory methods to return these instances.

 

Q18. Is Session a thread-safe object? what configuration do we have to do to make it thread-safe

Ans: No, Session is not a thread-safe object, many threads can access it simultaneously. In other words, you can share it between threads. 

To make the session thread safe we have to add the following property in the hibernate configuration file

<property name=”hibernate.current_session_context_class”>thread</property>

 

Q19. What is the difference between session.save() and session.persist() method?

  1. i) save (): returns the identifier (Serializable) of the instance

Syntax: public Serializable save(Object o)

ii)persist (): Return nothing because its return type is void.

Syntax: public void persist(Object o)

 

Q20. What is the difference between the update and merge methods of hibernate

Ans: update (): Reattaches a detached entity to the session and makes it managed. It requires the entity to not already exist in the session; otherwise, it throws an exception.

merge (): Copies the state of a detached entity into a new or existing managed entity. It’s safer to use if the entity might already exist in the session or has been modified elsewhere.

 

Q21 What are Hibernate annotations?

Ans: Hibernate annotations are used to provide metadata directly in Java classes, eliminating the need for XML mapping files

 

Q22 What are the states of the object in hibernate?

Ans: There are 3 states of the object (instance) in hibernate.

Transient: The object is in a transient state if it is just created but has no primary key (identifier) and is not associated with a session.

Persistent: The object is in a persistent state if a session is open, and you just saved the instance in the database or retrieved the instance from the database.

Detached: The object is in a detached state if a session is closed. After the detached state, the object comes to a persistent state if you call the lock() or update() method.

 

Q23. What are the inheritance mapping strategies?

Ans: There are 3 ways of inheritance mapping in hibernate.

Table per hierarchy

Table per concrete class

Table per subclass

 

Q24. What is HQL (Hibernate Query Language)?

Ans: Hibernate Query Language is known as an object-oriented query language. It is like a structured query language (SQL).

The main advantage of HQL over SQL is:

  • You don’t need to switch between SQL and JAVA code to write a query
  • Database independent
  • Simple to write a query

 

Q25. What is the difference between first-level cache and second-level cache?

Ans: 

First Level Cache:

  1. It is enabled by default.
  2. First Level Cache is associated with Session.

Second Level Cache:

  1. It is not enabled by default.
  2. The second Level Cache is associated with SessionFactory.

 

Q26. How does Hibernate handle transactions?

Ans: Hibernate provides transaction management through the Transaction interface. You can commit or roll back transactions.

 

Q27. Explain the use of the @Entity and @Table annotations.

Ans:

@Entity: Marks a class as a persistent entity.

@Table: Specifies the database table for the entity.

 

Q28. What is the use of hibernate dialect 

Ans: Hibernate dialect property defines how query will be formed based on databases used

hibernate dialect can be MysqlDialect or OracleDialect, so if we set MySQLDialect then hibernate creates

underneath queries in MySQL and if we choose OracleDialect then hibernate creates a query in Oracle

 

Q29. What are some common performance optimization techniques in Hibernate?

Ans:

  • Enable caching.
  • Use batch fetching.
  • Avoid unnecessary lazy loading.
  • Optimize HQL/SQL queries.
  • Use projections and pagination.

 

Q30. What are lazy loading and early loading how to use them in hibernate

Ans: Lazy Loading: data is fetched only when it will be accessed 

Eager loading: data is fetched immediately with a query

Uses:

Lazy Loading is better when:

When related data is rarely accessed.

For large collections or relationships that might be expensive to load and are not needed immediately.

When fine-grained control over database access is required.

Eager Loading is better when:

The related data is always required.

You want to avoid LazyInitializationException issues.

The relationships are small and won’t significantly impact performance.

Example:

 Using get(): Entity is loaded immediately

Employee emp = session.get(Employee.class, 1L); // Executes a SELECT query immediately

 

Using load(): Entity is loaded lazily

Employee emp = session.load(Employee.class, 1L); // No SELECT query yet

String name = emp.getName(); // Executes SELECT query now

Advantages Lazy Loading:

  1. Performance Optimized by fetching only when needed
  2. 3Memory Usage Lower, as unused data is not loaded
  3. Number of Queries Multiple queries for lazy associations
  4. Risk of Exceptions LazyInitializationException risk
  5. Best For Large collections or infrequently used data

Advantages Eager Loading:

  1. May fetch unnecessary data upfront
  2. 3Higher, due to preloading of related data
  3. Single query for all data
  4. No such risk
  5. Frequently accessed related data

 

Note: Do watch our latest video: Click Here

 

Author:-

Shital Chauhan
Call the Trainer and Book your free demo class for Java now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.