Hibernate Interview Questions and Answers

Thumb

Author

BIQ

Questions

24

Last updated

Feb 10, 2023

Hibernate or Hibernate ORM is a framework and a mapping tool for Java. It is an object-relational mapping tool that gives an object-oriented domain model to the relational database. The structure is able to handle the problems of object-relational impedance mismatch by the replacement of persistent and direct database access with the functions of high-level object handling functions. There are several Hibernate Interview Questions which must be learned by the students to give their best shot and get the desired job.

Advantages of Hibernate

  • Database independent can work with DB2, SQL, MySQL, Oracle, etc.
  • Get the benefits of OOP Concepts such as encapsulation, inheritance, etc.
  • No requirement of hitting database for related queries, directly cache it and use it
  • Easy to write, support and read
  • Lazy loading is possible

Most Frequently Asked Hibernate Interview Questions

Here in this article, we will be listing frequently asked Hibernate Interview Questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

Q1. What is hibernate and why it is used?
Answer

It is an ORM developed for mapping tool for Java application program. It has been used in the development of Java application program as the primary function of Hibernate ORM is mapping the classes to the database tables and the types of Java data to SQL data types.

Other uses are-
  • Retrieving the data results
  • Writing data queries
  • Solves the problems of the mismatch of the traditional object and relational impedance issue
Q2. What is the benefit of using Hibernate?
Answer

Hibernate is a popular Java-based framework for developing persistent data storage solutions, and it offers several benefits:

  • Simplifies database operations: Hibernate eliminates the need for manual data handling and reduces the complexity of database operations by providing a high-level API for working with data.
  • Increases developer productivity: Hibernate abstracts away the underlying database technology, allowing developers to focus on the business logic rather than writing low-level SQL queries.
  • Improved performance: Hibernate provides features such as caching and lazy loading that can significantly improve the performance of your application.
  • Supports multiple databases: Hibernate is database agnostic, meaning it can be used with any relational database management system. This allows developers to switch between databases without having to change their code.
  • Easy to maintain: Hibernate provides a flexible and extensible architecture that makes it easy to maintain and evolve your data storage solutions over time.

Overall, Hibernate provides a convenient and efficient way to work with data, making it a popular choice for many Java-based applications.

Q3. What is the Java Persistence API used for?
Answer

Java API or known as JPA is an interface specification of Java application program. It is used to describes the relational data’s management in the Java-based applications along with Enterprise Edition and Java platform.

Q4. How many types of transaction are there in hibernate?
Answer

There are four transactions in Hibernate ORM, and these are Atomicity, Consistency, Isolation, and Durability. Acronym used is ACID. These are the properties which every transaction follows.

Q5. What is transaction commit in Hibernate?
Answer

Transaction commit in Hibernate is a process that marks the end of a transaction and signals the database to make the changes permanent. When a transaction commit is executed, all changes made within the transaction are saved to the database and the transaction is closed. The commit operation is used to persist the changes to the database and ensure data integrity and consistency. If a transaction is not committed, any changes made within the transaction are rolled back and not saved to the database.

Q6. What is flush in hibernate?
Answer

The procedure of synchronizing the persistence context state with the database is known as flushing. There are a set of methods sent by Hibernate Session and EntityManager with the help of which the persistence state of an entity can be changed by the application developer.

Q7. What is the difference between save() and merge() in Hibernate?
Answer

Save and merge are two methods in Hibernate that are used to persist entities in the database. However, they have different purposes and implications:

1. Save: The save method is used to insert a new entity into the database. It generates a new ID for the entity and sets its state to persistent. If the entity already exists in the database, an exception is thrown.

2. Merge: The merge method is used to update an existing entity in the database or insert a new entity if it does not already exist. Unlike save, merge does not generate a new ID for the entity and does not change its state to persistent. Instead, it returns a managed entity that is in sync with the state of the database.

In summary, save is used for inserting new entities, while the merge is used for updating existing entities or inserting new entities if they do not exist.

Q8. What is the use of evicting method in hibernate?
Answer

The evict method is used for detaching the object from hibernate provides evict () method and session cache. After this process, there is no persistence in the change of the object. The detachment of the associated objects can also take place with the mapping associated with the cascade=” evict.”

Q9. What is Hibernate session factory?
Answer

Hibernate SessionFactory is an interface, and it is created with the help of Configuration object. It consists of all the database related property details and in this, either hibernate.properties, the hibernate.cfg.xml file is used for pulling it. In the case of the increased number of multiple databases, then the requirement of creating one SessionFactory per database.

Q10. Why is SessionFactory used in hibernate?
Answer

Session Factory is used to configure objects which is further responsible for allowing instantiation of the Session object and turning the configuration Hibernation for supplied configuration file application. Threads of an application use SessionFactory in Hibernation.

Q11. What is the difference between hibernate save () saveOrUpdate () and persist () methods?
Answer
S.no Hibernate Save() SaveorUpdate method()
1. Work to generate a new identifier and then inserting the record into the database It either can UPDATE or INSERT because as per the existence of record.save() method can be failed with the persistence of the primary key
2. Used for bringing a transient object to a persisting state It can bring both new and existing, i.e., transient and detached into a persistent state or can be said that this method can be used for re-attaching a detached object into Session
Q12. What are the steps of calling a stored procedure in hibernate?
Answer
Write the following queries-

1. Use CreateNativeSQL Method for calling a procedure

  • Query query = session.createSQLQuery (“CALL GetAllFoos ()”).addEntity;
  • List allFoos= query.list();

2. Use @NamedNativeQueries to call a stored procedure

3. Use @NamedStoreProcedureQuery to call a stored procedure

Use @NamedNativeQueries to call a stored procedure

@NamedNativeQueries({

          @NamedNativeQuery(

   name = "callGetAllFoos",

   query = "CALL GetAllFoos()",

      resultClass = Foo.class)

                         })

@Entity

public class Foo implements Serializable {

         // Model definition

}

Use @NamedStoreProcedureQuery to call a stored procedure

@NamedStoredProcedureQuery(

     name="GetAllFoos",

     procedureName="GetAllFoos",

     resultClasses = { Foo.class }

  )

@Entity

public class Foo implements Serializable {

 // Model Definition

}

Q13. Explain the difference between Criteria and Criterion in Hibernate?
Answer

In Hibernate, criteria and criterion are two important concepts related to data retrieval from a database.

Criteria: Criteria refers to a query that is used to retrieve data from a database using the Hibernate Criteria API. Criteria provide a flexible and dynamic approach to creating complex queries for retrieving data from a database.

Criterion: Criterion refers to a specific condition that is used to filter the data in a criteria query. For example, you can use a criterion to filter the data based on a specific attribute value, range of values, or a combination of values.

In other words, criteria are the overall query and criterion is a specific condition within the query that is used to filter the data.

Q14. What is the difference between SessionFactory and session in hibernate?
Answer
S.no SessionFactory objects Session
1. There is one SessionFactory object per application There is one Session object per client
2. Used for creation and management and it is threaded safe Sessions Session is not threaded safe and give CRUD interface to the mapped classes
Q15. List some of the database support by hibernate?
Answer
Hibernate use SQL databases for regularly testing by regularly handling in the Hibernate product lifecycle or Hibernate developers:
  • Oracle 11g, 11g RAC
  • MySQL 5.1, 5.5.
  • PostgreSQL 8.4, 9.1
  • DB2 9.7 or above.
  • Microsoft SQL Server 2008.
  • Sybase ASE 15.5 (jConnect 6.0)
Q16. Why is Hibernate called ORM?
Answer

Hibernate offers retrieval facilities and data query services along with generating SQL calls and relaxing the developer from handling the project manually and conversion of the object of the set of the result. These are the reasons which make Hibernate an object-relational model for the mapping tool for Java language.

Q17. What are the states of the object in hibernate?
Answer
Hibernate object states are as follows-
  • Detached Object State
  • Persistent Object State
  • Transient Object State
Q18. What are the main differences between persistent and transient objects?
Answer
S.no Persistent Objects Transient Objects
1. In this state, the database has the saved objects The objects are not kept in the database in this state of Hibernation
2. Example- An entity from a repository comes under persistent objects Until persisted, the creation of a new entity is called transients
Q19. Why do we need transactions in hibernate?
Answer

Transactions are required for protecting and maintaining the data and their consistency in Hibernate. Java application program framework, can modify several things in the databases, but transactions are needed for retaining the database and for this, there is an availability of Transaction Interface.

Q20. How to Implement Database Relationship in Hibernate?
Answer

Hibernate supports several types of database relationships, including one-to-one, one-to-many, many-to-one, and many-to-many relationships. These relationships can be implemented in Hibernate by using annotations or XML mapping files.

Types of Database Relationships

  • One-to-One Relationship
  • One-to-Many Relationship
  • Many-to-One Relationship
  • Many-to-Many Relationship

1. One-to-One Relationship: To implement a one-to-one relationship in Hibernate, we can use the @OneToOne annotation on the primary key side of the relationship. The join column is specified using the @JoinColumn annotation.

Example:

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToOne
@JoinColumn(name = "address_id")
private Address address;
}

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String street;
private String city;
private String state;
}

2. One-to-Many Relationship: To implement a one-to-many relationship in Hibernate, we can use the @OneToMany annotation on the many side of the relationship. The mappedBy attribute specifies the inverse side of the relationship.

Example:

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToMany(mappedBy = "department")
private List employees;
}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}

3. Many-to-One Relationship: To implement a many-to-one relationship in Hibernate, we can use the @ManyToOne annotation on the many side of the relationship. The join column is specified using the @JoinColumn annotation.

Example:

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToMany(mappedBy = "department")
private List employees;
}

4. Many-to-Many Relationship: To implement a many-to-many relationship in Hibernate, we can use the @ManyToMany annotation. A join table is required to map the relationship.

Example:

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "employee_project",
joinColumns = { @JoinColumn

Q21. What is the default annotation for a property in hibernate?
Answer

The default annotation for a property in the Java framework is a @ld annotation, where Hibernate assumes that the annotation is on the object’s access properties and detects that it is on the field. Placing the annotation @ld on getId() method gives access to the features through getter and setter methods and that too by default.

Q22. What is a configuration in hibernate?
Answer

Configuration settings are required for the database and various other related parameters in Hibernate. The format for displaying such information is supplied as an XML file named hibernate.cffg.xml and hibernate.properties know as standard Java properties file.

Q23. What is Hibernate mapping file?
Answer

The object or relational mappings are the files which are defined in an XML document which instruct Hibernate in mapping the defined classes or class to the tables in the database.

Q24. What is the difference between JDBC and Hibernate?
Answer
S.no JDBC Hibernate
1. Standard API ORM (Object-Relational Mapping)
2. Java applications used JDBC for communicating with the database Used for mapping Java objects to a corresponding relational database.

To read more Hibernate Interview Questions, and make the concepts clear, you can visit the Best Interview Question.