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.
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.
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.
Hibernate is a popular Java-based framework for developing persistent data storage solutions, and it offers several benefits:
Overall, Hibernate provides a convenient and efficient way to work with data, making it a popular choice for many Java-based applications.
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.
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.
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.
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.
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.
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.”
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.
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.
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 |
1. Use CreateNativeSQL Method for calling a procedure
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
}
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.
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 |
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.
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 |
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.
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.
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
}
@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
}
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
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.
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.
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.
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.