Hibernate Interview Questions
What is a Session in Hibernate?
A session is an object that maintains the connection between Java object application and database. Session also has methods for storing, retrieving, modifying or deleting data from database using methods like persist(), load(), get(), update(), delete(), etc. Additionally, It has factory methods to return Query, Criteria, and Transaction objects.
What is a SessionFactory?
SessionFactory provides an instance of Session. It is a factory class that gives the Session objects based on the configuration parameters in order to establish the connection to the database.
As a good practice, the application generally has a single instance of SessionFactory. The internal state of a SessionFactory which includes metadata about ORM is immutable, i.e once the instance is created, it cannot be changed.
What is the difference between first level cache and second level cache?
Hibernate has 2 cache types. First level and second level cache for which the difference is given below:
First Level Cache | Second Level Cache |
---|---|
This is local to the Session object and cannot be shared between multiple sessions. | This cache is maintained at the SessionFactory level and shared among all sessions in Hibernate. |
This cache is enabled by default and there is no way to disable it. | This is disabled by default, but we can enable it through configuration. |
The first level cache is available only until the session is open, once the session is closed, the first level cache is destroyed. | The second-level cache is available through the application’s life cycle, it is only destroyed and recreated when an application is restarted. |
What can you tell about Hibernate Configuration File?
Hibernate Configuration File or hibernate.cfg.xml is one of the most required configuration files in Hibernate. By default, this file is placed under the src/main/resource folder.
The file contains database related configurations and session-related configurations.
Hibernate facilitates providing the configuration either in an XML file (like hibernate.cfg.xml) or a properties file (like hibernate.properties).
This file is used to define the below information:
- Database connection details: Driver class, URL, username, and password.
- There must be one configuration file for each database used in the application, suppose if we want to connect with 2 databases, then we must create 2 configuration files with different names.
- Hibernate properties: Dialect, show_sql, second_level_cache, and mapping file names.
What are the most commonly used annotations available to support hibernate mapping?
Hibernate framework provides support to JPA annotations and other useful annotations in the org.hibernate.annotations package. Some of them are as follows:
- javax.persistence.Entity: This annotation is used on the model classes by using “@Entity” and tells that the classes are entity beans.
- javax.persistence.Table: This annotation is used on the model classes by using “@Table” and tells that the class maps to the table name in the database.
- javax.persistence.Access: This is used as “@Access” and is used for defining the access type of either field or property. When nothing is specified, the default value taken is “field”.
- javax.persistence.Id: This is used as “@Id” and is used on the attribute in a class to indicate that attribute is the primary key in the bean entity.
- javax.persistence.EmbeddedId: Used as “@EmbeddedId” upon the attribute and indicates it is a composite primary key of the bean entity.
- javax.persistence.Column: “@Column” is used for defining the column name in the database table.
- javax.persistence.GeneratedValue: “@GeneratedValue” is used for defining the strategy used for primary key generation. This annotation is used along with javax.persistence.GenerationType enum.
- javax.persistence.OneToOne: “@OneToOne” is used for defining the one-to-one mapping between two bean entities. Similarly, hibernate provides OneToMany, ManyToOne and ManyToMany annotations for defining different mapping types.
org.hibernate.annotations.Cascade: “@Cascade” annotation is used for defining the cascading action between two bean entities. It is used with org.hibernate.annotations.CascadeType enum to define the type of cascading.
Hibernate framework provides support to JPA annotations and other useful annotations in the org.hibernate.annotations package. Some of them are as follows:
- javax.persistence.Entity: This annotation is used on the model classes by using “@Entity” and tells that the classes are entity beans.
- javax.persistence.Table: This annotation is used on the model classes by using “@Table” and tells that the class maps to the table name in the database.
- javax.persistence.Access: This is used as “@Access” and is used for defining the access type of either field or property. When nothing is specified, the default value taken is “field”.
- javax.persistence.Id: This is used as “@Id” and is used on the attribute in a class to indicate that attribute is the primary key in the bean entity.
- javax.persistence.EmbeddedId: Used as “@EmbeddedId” upon the attribute and indicates it is a composite primary key of the bean entity.
- javax.persistence.Column: “@Column” is used for defining the column name in the database table.
- javax.persistence.GeneratedValue: “@GeneratedValue” is used for defining the strategy used for primary key generation. This annotation is used along with javax.persistence.GenerationType enum.
- javax.persistence.OneToOne: “@OneToOne” is used for defining the one-to-one mapping between two bean entities. Similarly, hibernate provides OneToMany, ManyToOne and ManyToMany annotations for defining different mapping types.
org.hibernate.annotations.Cascade: “@Cascade” annotation is used for defining the cascading action between two bean entities. It is used with org.hibernate.annotations.CascadeType enum to define the type of cascading.
Explain Hibernate architecture
The Hibernate architecture consists of many objects such as a persistent object, session factory, session, query, transaction, etc. Applications developed using Hibernate is mainly categorized into 4 parts:
- Java Application
- Hibernate framework - Configuration and Mapping Files
- Internal API -
- JDBC (Java Database Connectivity)
- JTA (Java Transaction API)
- JNDI (Java Naming Directory Interface).
- Database - MySQL, PostGreSQL, Oracle, etc
The main elements of Hibernate framework are:
- SessionFactory: This provides a factory method to get session objects and clients of ConnectionProvider. It holds a second-level cache (optional) of data.
- Session: This is a short-lived object that acts as an interface between the java application objects and database data.
- The session can be used to generate transaction, query, and criteria objects.
- It also has a mandatory first-level cache of data.
- Transaction: This object specifies the atomic unit of work and has methods useful for transaction management. This is optional.
- ConnectionProvider: This is a factory of JDBC connection objects and it provides an abstraction to the application from the DriverManager. This is optional.
- TransactionFactory: This is a factory of Transaction objects. It is optional.
The Hibernate architecture consists of many objects such as a persistent object, session factory, session, query, transaction, etc. Applications developed using Hibernate is mainly categorized into 4 parts:
- Java Application
- Hibernate framework - Configuration and Mapping Files
- Internal API -
- JDBC (Java Database Connectivity)
- JTA (Java Transaction API)
- JNDI (Java Naming Directory Interface).
- Database - MySQL, PostGreSQL, Oracle, etc
The main elements of Hibernate framework are:
- SessionFactory: This provides a factory method to get session objects and clients of ConnectionProvider. It holds a second-level cache (optional) of data.
- Session: This is a short-lived object that acts as an interface between the java application objects and database data.
- The session can be used to generate transaction, query, and criteria objects.
- It also has a mandatory first-level cache of data.
- Transaction: This object specifies the atomic unit of work and has methods useful for transaction management. This is optional.
- ConnectionProvider: This is a factory of JDBC connection objects and it provides an abstraction to the application from the DriverManager. This is optional.
- TransactionFactory: This is a factory of Transaction objects. It is optional.
Can you tell the difference between getCurrentSession and openSession methods?
Both the methods are provided by the Session Factory. The main differences are given below:
getCurrentSession() openSession() This method returns the session bound to the context. This method always opens a new session. This session object scope belongs to the hibernate context and to make this work hibernate configuration file has to be modified by adding <property name = "hibernate.current_session_context_class"> thread </property>. If not added, then using the method would throw an HibernateException. A new session object has to be created for each request in a multi-threaded environment. Hence, you need not configure any property to call this method. This session object gets closed once the session factory is closed. It's the developer’s responsibility to close this object once all the database operations are done. In a single-threaded environment, this method is faster than openSession(). In single threaded environment, it is slower than getCurrentSession()single-threadeda
Both the methods are provided by the Session Factory. The main differences are given below:
getCurrentSession() | openSession() |
---|---|
This method returns the session bound to the context. | This method always opens a new session. |
This session object scope belongs to the hibernate context and to make this work hibernate configuration file has to be modified by adding <property name = "hibernate.current_session_context_class"> thread </property>. If not added, then using the method would throw an HibernateException. | A new session object has to be created for each request in a multi-threaded environment. Hence, you need not configure any property to call this method. |
This session object gets closed once the session factory is closed. | It's the developer’s responsibility to close this object once all the database operations are done. |
In a single-threaded environment, this method is faster than openSession(). | In single threaded environment, it is slower than getCurrentSession()single-threadeda |
Differentiate between save() and saveOrUpdate() methods in hibernate session.
Both the methods save records to the table in the database in case there are no records with the primary key in the table. However, the main differences between these two are listed below:
save() saveOrUpdate() save() generates a new identifier and INSERT record into a database Session.saveOrUpdate() can either INSERT or UPDATE based upon existence of a record. The insertion fails if the primary key already exists in the table. In case the primary key already exists, then the record is updated. The return type is Serializable which is the newly generated identifier id value as a Serializable object. The return type of the saveOrUpdate() method is void. This method is used to bring only a transient object to a persistent state. This method can bring both transient (new) and detached (existing) objects into a persistent state. It is often used to re-attach a detached object into a Session
Both the methods save records to the table in the database in case there are no records with the primary key in the table. However, the main differences between these two are listed below:
save() | saveOrUpdate() |
---|---|
save() generates a new identifier and INSERT record into a database | Session.saveOrUpdate() can either INSERT or UPDATE based upon existence of a record. |
The insertion fails if the primary key already exists in the table. | In case the primary key already exists, then the record is updated. |
The return type is Serializable which is the newly generated identifier id value as a Serializable object. | The return type of the saveOrUpdate() method is void. |
This method is used to bring only a transient object to a persistent state. | This method can bring both transient (new) and detached (existing) objects into a persistent state. It is often used to re-attach a detached object into a Session |
Differentiate between get() and load() in Hibernate session
These are the methods to get data from the database. The primary differences between get and load in Hibernate are given below:
get() load() This method gets the data from the database as soon as it is called. This method returns a proxy object and loads the data only when it is required. The database is hit every time the method is called. The database is hit only when it is really needed and this is called Lazy Loading which makes the method better. The method returns null if the object is not found. The method throws ObjectNotFoundException if the object is not found. This method should be used if we are unsure about the existence of data in the database. This method is to be used when we know for sure that the data is present in the database.
These are the methods to get data from the database. The primary differences between get and load in Hibernate are given below:
get() | load() |
---|---|
This method gets the data from the database as soon as it is called. | This method returns a proxy object and loads the data only when it is required. |
The database is hit every time the method is called. | The database is hit only when it is really needed and this is called Lazy Loading which makes the method better. |
The method returns null if the object is not found. | The method throws ObjectNotFoundException if the object is not found. |
This method should be used if we are unsure about the existence of data in the database. | This method is to be used when we know for sure that the data is present in the database. |
What is HQL?
Hibernate Query Language (HQL) is used as an extension of SQL. It is very simple, efficient, and very flexible for performing complex operations on relational databases without writing complicated queries. HQL is the object-oriented representation of query language, i.e instead of using table name, we make use of the class name which makes this language independent of any database.
This makes use of the Query interface provided by Hibernate. The Query object is obtained by calling the createQuery() method of the hibernate Session interface.
Following are the most commonly used methods of query interface:
- public int executeUpdate() : This method is used to run the update/delete query.
- public List list(): This method returns the result as a list.
- public Query setFirstResult(int rowNumber): This method accepts the row number as the parameter using which the record of that row number would be retrieved.
- public Query setMaxResult(int rowsCount): This method returns a maximum up to the specified rowCount while retrieving from the database.
- public Query setParameter(int position, Object value): This method sets the value to the attribute/column at a particular position. This method follows the JDBC style of the query parameter.
- public Query setParameter(String name, Object value): This method sets the value to a named query parameter.
Hibernate Query Language (HQL) is used as an extension of SQL. It is very simple, efficient, and very flexible for performing complex operations on relational databases without writing complicated queries. HQL is the object-oriented representation of query language, i.e instead of using table name, we make use of the class name which makes this language independent of any database.
This makes use of the Query interface provided by Hibernate. The Query object is obtained by calling the createQuery() method of the hibernate Session interface.
Following are the most commonly used methods of query interface:
- public int executeUpdate() : This method is used to run the update/delete query.
- public List list(): This method returns the result as a list.
- public Query setFirstResult(int rowNumber): This method accepts the row number as the parameter using which the record of that row number would be retrieved.
- public Query setMaxResult(int rowsCount): This method returns a maximum up to the specified rowCount while retrieving from the database.
- public Query setParameter(int position, Object value): This method sets the value to the attribute/column at a particular position. This method follows the JDBC style of the query parameter.
- public Query setParameter(String name, Object value): This method sets the value to a named query parameter.
What are Many to Many associations?
Many-to-many association indicates that there are multiple relations between the instances of two entities. We could take the example of multiple students taking part in multiple courses and vice versa.
Since both the student and course entities refer to each other by means of foreign keys, we represent this relationship technically by creating a separate table to hold these foreign keys.
Many-to-many association indicates that there are multiple relations between the instances of two entities. We could take the example of multiple students taking part in multiple courses and vice versa.
Since both the student and course entities refer to each other by means of foreign keys, we represent this relationship technically by creating a separate table to hold these foreign keys.
Comments
Post a Comment