Hibernate Interview Questions and Answers | Top 150 Hibernate Questions

Top 150 Hibernate Questions and Answers for Job Interview :

1. What is Hibernate Framework?

Answer : Object-relational mapping (ORM) is a programming technique used to map application domain model objects to relational database tables and vice versa. It provides reference implementation of Java Persistence API which makes it a great choice as an ORM tool with benefits of loose coupling. Hibernate persistence API is used for CRUD operations. The framework provides options to map plain old objects to traditional database tables with the use of JPA annotations and XML-based configuration.

2. What is Java Persistence API (JPA)?

Answer : It provides specification for managing the relational data in applications.

3. What is Hibernate Session Factory and how to configure it?

Answer : It is the factory class used to get the Session objects, Session Factory is responsible to read hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single Session Factory instance and the threads servicing client requests obtain the Session instances from the same factory. The internal state of a Session Factory is immutable, i.e., once it is created, the internal state is set. This internal state includes all the metadata about Object and Relational Mapping. It also provide methods to get the Class metadata and Statistics instance to get the statistics of query executions, second level cache details, etc. The internal state of Session Factory is immutable, so it is thread safe. Multiple threads can access the internal state simultaneously to get Session instances.

4. What is Hibernate Session and how to get it?

Answer : The interface between a Java application layer and Hibernate is known as Hibernate Session. It is the core interface used to perform database operations. The lifecycle of any session is bound by the beginning and end of a transaction. The session provides methods to perform operations line create, read, update and delete for a persistent object. We can execute SQL native queries, HQL queries and create criteria using Session objects.

5. What is difference between openSession() and getCurrentSession() methods?

Answer : The getCurrentSession() method returns the session bound to the context. However, we need to configure it in the Hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed automatically. The openSession() method always opens a new session. This session object needs to be closed once all the database operations are completed. A new session must be opened for each request in a multi-threaded environment.

6. What is difference between Hibernate Session get() and load() methods?

Answer : Any Hibernate session comes with different methods to load data from database. The get() and load() methods are most used ones. The get() method loads the data as soon as the method is invoked whereas the load() method returns a proxy object and loads data only when it’s actually required. Hence, the load() method is better because it supports lazy loading. Since the load() method throws exception when data is not found, we should use it only when we know data actually exists. We can use the get() method when we want to make sure the data exists in the database.

7. What is hibernate caching? Explain Hibernate first level cache?

Answer : Hibernate caches query data to make our application faster. It is very useful in gaining fast application performance if used correctly. The idea behind any kind of cache is to reduce the number of database queries, hence reducing the throughput time of the application. Hibernate first level cache is associated with Session object. Hibernate first level cache is enabled by default and it cannot be disabled. However, hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. Any object cached in a session will be invisible to other sessions and when the session is closed, all the cached objects will also be lost.

8. What are different states of an entity bean?

Answer : An entity bean instance can exist in one of the three states.

Answer : Transient:When any object is never associated with any session or persistent, it’s in its transient state. Such instances can be made persistent by calling the save(), persist() or saveOrUpdate() methods. Persistent instances can be made transient by calling the delete() method.

Persistent:When any object is associated with a unique session, it’s in its persistent state. Any instance returned by the get() or load() method is persistent.

Detached:When an object is persistent but not associated with any session, it’s in its detached state. Detached instances can be made persistent by calling the update(), saveOrUpdate(), lock() or replicate() methods. The state of a transient or detached instance can also be made persistent as a new persistent instance by calling the merge() method.

9. How to implement the joins() in Hibernate?

Answer : There are various ways to implement the joins() in Hibernate. Using associations such as the one-to-one, one-to-many etc. There is another form known as the join fetch method that is used to load associated data simultaneously. We can also fire native SQL query and use ‘join’ keyword.

10. What is HQL and what are its benefits?

Answer : The Hibernate Framework comes with a powerful object-oriented query language known as Hibernate Query Language (HQL). It is similar to SQL except the fact that objects are used instead of table names. This makes it more close to OOP. HQL is case-insensitive except for Java classes and variable names. HQL queries are cached but they must be avoided otherwise we will have to take care of associations. It is a better choice than native SQL query because of its Object-Oriented approach.

11. What is Query Cache in Hibernate?

Answer : Hibernate implements a cache region for queries result set that integrates closely with the Hibernate second-level cache. This is an optional feature and requires additional steps in code. This is only useful for queries that are run frequently with the same parameters. 

12. Can we execute native SQL query in Hibernate?

Answer : Hibernate provides option to execute native SQL queries through the use of SQLQuery object. For normal scenarios, this is not the recommended approach because we lose benefits related to Hibernate association and Hibernate first level caching.

13. What is the benefit of native SQL query support in Hibernate?

Answer : Native SQL Query comes in use when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in the Oracle Database.

14. What is Named SQL Query?

Answer : Hibernate provides Named Query that can be defined at a central location and can be used anywhere in the code. We can created named queries for both HQL and Native SQL. Hibernate Named Queries can be defined in Hibernate mapping files or by using JPA annotations @NamedQuery and @NamedNativeQuery.

15. What are the benefits of Named SQL Query?

Answer : Hibernate Named Query helps us in grouping queries at a central location instead of letting them be scattered all over the code. Hibernate Named Query syntax is checked when the Hibernate session factory is created. This makes the application fail fast in case of any error in the named queries. Hibernate Named Query is global in nature, i.e., once defined it can be used throughout the application. One of the major disadvantages of Named SQL Query is that it is hard to debug, because we need to find out the location of definition.

16. What is the benefit of Hibernate Criteria API?

Answer : Hibernate provides Criteria API which is more Object-oriented for querying the database and getting results. We can’t use Criteria API to run update or delete queries or any DDL statements. It is only used to fetch the results from the database using a more Object-oriented approach. Some of the common uses of Criteria API are:

  • It provides Projection that can be used for aggregate functions such as sum(), min(), max() etc.
    It can be used with ProjectionList to fetch selected columns only.
  • It can be used to join queries by joining multiple tables and by using methods such as createAlias(), setFetchMode() and setProjection()
  • It can also be used for fetching results with conditions. The add() method is one such useful method that can be used to add Restrictions.
  • It provides the addOrder() method that can be used for ordering the results.

17. What is Hibernate Proxy and how does it help lazy loading?

Answer : Hibernate uses proxy objects to support lazy loading. When data is loaded from tables, Hibernate doesn’t load all the mapped objects. As soon as a child or lookup object is rounded up via the getter() methods, if the linked entity is not in the session cache, then the proxy code goes to the database and loads the linked object. It uses Java Assist to effectively and dynamically generate sub-classed implementations of your entity objects.

18. How to implement relationships in hibernate?

Answer : We can easily implement one-to-one, one-to-many and many-to-many relationships in Hibernate. It can be done using JPA annotations as well as XML based configurations.

19. How does the transaction management work in Hibernate?

Answer : Transaction management is very easy in Hibernate because most of the operations are not permitted outside the transaction. After getting the session from SessionFactory, we can call the session by using the beginTransaction() to start the transaction. This method returns the Transaction reference that can be used later to either commit or rollback the transaction. Hibernate transaction management is better than the JDBC transaction management because we don’t need to rely on exceptions for rollbacks. Any exception thrown by the session methods automatically rollbacks the transaction.

20. What is cascading and what are different types of cascading?

Answer : When we have relationship between entities, we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it. Note that Hibernate CascadeType enum constants are different from JPA    javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings.
Commonly used cascading types as defined in CascadeType enum are:

  • None:This is not a type but when we don’t define any cascading then no operations in parent affects the child.
  • ALL:Cascades save, delete, update, evict, lock, replicate, merge, and persist.
  • SAVE_UPDATE:Cascades save and update, available only in Hibernate.
  • DELETE:Corresponds to the Hibernate native DELETE action, only in Hibernate.
  • DETATCH, MERGE, PERSIST, REFRESH and REMOVE – They have similar operations.
  • LOCK:This corresponds to the Hibernate native LOCK action.
  • REPLICATE:This corresponds to the Hibernate native REPLICATE action.

21. What is ORM?

Answer : ORM stands for Object Relational Mapping. It is the automated persistence of objects in a Java application to the tables in a relational database.

22. What does ORM consist of?

Answer : An ORM solution consists of the following four pieces:

  • API to express queries referring to classes
  • Facilities to specify metadata
  • Optimization facilities : dirty checking, lazy associations fetching
  • API for performing basic CRUD operations

23. What are the ORM levels?

Answer : The ORM levels are:

  • Pure relational (stored procedure.)
  • Light objects mapping (JDBC)
  • Medium object mapping
  • Full object Mapping (composition, inheritance, polymorphism, persistence by reachability)

24. Why do you need ORM tools like Hibernate?

Answer : The main advantage of ORM like Hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

Improved Productivity

  • High-Level Object-Oriented API
  • Less code to write
  • No SQL to write

Improved Performance

  • Sophisticated Caching
  • Lazy Loading
  • Eager Loading

Improved Maintainability

  • Very less code to write

Improved Portability

  • ORM framework generates Database-specific SQL for you

25. What Does Hibernate Simplify?

Answer : Hibernate simplifies saving and retrieving your domain objects, making database column and table name changes, centralizing pre save and post retrieve logic, schema creation from object model and complex joins for retrieving related items.

26. What is the need for Hibernate XML mapping file?

Answer : Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. 

27. What are the most common methods of Hibernate configuration?

Answer : The most common methods of Hibernate configuration are: Programmatic configuration and XML configuration (hibernate.cfg.xml).

28. What are the Core interfaces are of Hibernate framework?

Answer : The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

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

29. What role does the Session interface play in Hibernate?

Answer : The Session Interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

30. What role does the Session Factory interface play in Hibernate?

Answer : The application obtains Session instances from a Session Factory. Typically there is a single Session Factory for the whole application—created during application initialization. The Session Factory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work.

SessionFactory sessionFactory = configuration.buildSessionFactory();

31. What is the general flow of Hibernate communication with RDBMS?

Answer : The general flow of Hibernate communication with RDBMS is :

  • Load the Hibernate configuration file and create a configuration object. It will automatically load all HBM mapping files.
  • Create a Session Factory from configuration object.
  • Get one session from this Session Factory.
  • Create a HQL Query.
  • Execute Query to get list containing Java objects.

32. What is Hibernate Query Language (HQL)?

Answer : Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. The Hibernate query Language (HQL), is an object-oriented extension to SQL.

33. How do you map Java Objects with Database tables?

Answer : First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.

For Example:

<hibernate-mapping>
<class name=”com.test.User”  table=”user”>
<property  column=”USER_NAME” length=”255″
name=”userName” not-null=”true”  type=”java.lang.String”/>
<property  column=”USER_PASSWORD” length=”255″
name=”userPassword” not-null=”true”  type=”java.lang.String”/>
</class>
</hibernate-mapping>

34. What is the difference between and merge() and update()?

Answer : The update() method is used if you are sure that the session does not contain an already persistent instance with the same identifier, and the merge() method is used if you want to merge your modifications at any time without consideration of the state of the session.

35. How do you define sequence generated primary key in Hibernate?

Answer : Usually we define Sequence Generated using <generator> tag.

For Example:

<id column=”USER_ID” name=”id” type=”java.lang.Long”>
<generator>
<param name=”table”>SEQUENCE_NAME</param>
   <generator>
</id>

36. Define cascade and inverse option in one-many mapping.

Answer : The cascade method enables operations to cascade to child entities.
Example: cascade=”all|none|save-update|delete|all-delete-orphan”

The inverse method marks any collection as the “inverse” end of a bidirectional association.
For example: inverse=”true|false”

37. What do you mean by Named – SQL query?

Answer : Named SQL queries are defined in the mapping XML document and is called wherever required.

Example:

<sql-query name = “empdetails”>
<return alias=”emp”/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

The following code can be executed to invoke Named Query :

List people = session.getNamedQuery(“empdetails”)
.setString(“TomBrady”, name)
.setMaxResults(50)
.list();

38. How do you invoke Stored Procedures?

Answer : The following code can be executed to invoke Stored Procedures:

<sql-query name=”selectAllEmployees_SP” callable=”true”>
<return alias=”emp”>
<return-property name=”empid” column=”EMP_ID”/>
<return-property name=”name” column=”EMP_NAME”/>
<return-property name=”address” column=”EMP_ADDRESS”/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>

39. Explain Criteria API.

Answer : Criteria API is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set.

For Example:

List employees = session.createCriteria(Employee.class)
.add(Restrictions.like(“name”, “a%”) )
.add(Restrictions.like(“address”, “Boston”))
.addOrder(Order.asc(“name”) )
.list();

40. Define Hibernate Template.

Answer : The org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying and retrieving data from the database. It also converts checked Hibernate Exceptions into unchecked DataAccess Exceptions.

41. What are the benefits does Hibernate Template provide?

The benefits of using the Hibernate Template are :

  • The Spring Template class simplifies interactions with the Hibernate Session.
  • The common functions are simplified to single method calls.
  • The sessions are automatically closed.
  • All exceptions are automatically caught and converted to runtime exceptions.

42. How do you switch between relational databases without code changes?

Answer : Using Hibernate SQL Dialects, we can switch databases. Hibernate generates appropriate HQL queries based on the dialect defined.

43. If we want to see the Hibernate generated SQL statements on console, what should we do?

Answer : The following set of code must be followed in order to see the Hibernate generated SQL statements on the console:
<property name=”show_sql”>true</property>

44. What are derived properties?

Answer : The properties that are not mapped to a column but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

45. What is component mapping in Hibernate?

Answer : A component is an object saved as a value instead of a reference. A component can be saved directly without declaring interfaces or identifier properties. Component Mapping is required to define an empty constructor, however, shared references are not supported.

46. What are the Collection types in Hibernate?

Answer : Bag,Set, List, Array, Map are the collection types in Hibernate.

47. What are the ways to express joins in HQL?

Answer : HQL provides four ways of expressing the inner and outer joins:-

  • An implicitassociation join
  • An ordinary join in the FROM clause
  • A fetch join in the FROM clause.
  • theta-stylejoin in the WHERE clause.

48. How can Hibernate be configured to access an instance variable directly and not through a setter method?

Answer : By mapping the property with access=”field” in Hibernate metadata, an instance variable can be accessed directly. This forces Hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

49. How can a whole class be mapped as immutable?

Answer : To make a whole class immutable, the class must be marked as mutable=”false”. This specifies that instances of the class are not mutable. Immutable classes cannot be updated or deleted by the application.

50. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

Answer : Criteria APIis a simplified API for retrieving entities by composing the Criterion objects. This is a very convenient approach for functionality like search screens where there is a number of conditions to be placed upon the result set. The dynamic-update() method specifies that UPDATE SQL should be generated at runtime and can contain only those columns whose values have changed. The dynamic-insert() method specifies that INSERT SQL should be generated at runtime and can contain only the columns whose values are not null.

51. What do you mean by fetching strategy?

Answer :fetching strategy is the strategy Hibernate uses for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or can be over-ridden by a particular HQL or Criteria query.

52. What is automatic dirty checking?

Answer : Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

53. What is transactional write-behind?

Answer : Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable for the user. This feature is called transactional write-behind.

54. What are Callback interfaces?

Answer : Callback interfaces allow the application to receive a notification when something happens to an object.

For example, when an object is loaded, saved, or deleted the callback interface sends out a notification.

Hibernate applications don’t need to implement these callbacks, but they’re useful for implementing certain kinds of generic functionality.

55. What are the types of Hibernate instance states?

Answer : The three types of instance states are:

Transient –The instance is not associated with any persistence context.

Persistent -The instance is associated with a persistence context.

Detached -The instance was associated with a persistence context which has been closed and is currently not associated.

56. What are the differences between EJB 3.0 & Hibernate?

Answer : The following are the differences between EJB 3.0 and Hibernate:

  • Hibernate uses cache or collection of loaded objects relating to a single unit of work while EJB 3.0 uses persistence context which is a set of entities that can be managed by a given Entity Manager.
  • XDoclet Annotationsof Hibernate is used to support Attribute Oriented Programming while EJB 3.0 uses Java 5.0 Annotations used to support Attribute Oriented Programming.
  • Hibernate defines HQLfor expressing queries to the database and EJB defines EJB QL for expressing queries.
  • Hibernate uses Entity Relationshipsthrough mapping files and annotations in JavaDoc and EJB uses Entity Relationships through Java 5.0 annotations.
  • Hibernate provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API while EJB provides an Entity Manager Interface for managing CRUD operations for an Entity.
  • Hibernate provides callback supportthrough lifecycle, interceptor, and valid table interfaces and EJB provides callback support through Entity Listener and Callback methods.
  • Entity Relationships are unidirectional in Hibernate. Bidirectional relationships are implemented by two unidirectional relationships. In EJB, entity Relationships are bidirectional or unidirectional.

57. What are the types of inheritance models in Hibernate?

Answer : There are three types of inheritance models in Hibernate:

  • Table per class hierarchy
  • Table per subclass
  • Table per concrete class

58. Explain @UniqueConstraint and @Column Unique attribute.

Answer : The @UniqueConstraint and unique attribute of @Column instructs schema/DDL generation tool to generate the corresponding unique constraints however using that attributes on POJO doesn’t implement constraints itself.

59. Mention the ways of creating a SQL query in Hibernate.

Answer : There are three different ways we can create a SQL query in Hibernate.

  • session.createQuery()
  • session.createSQLQuery()
  • session.createCriteria()

60. Differentiate between @NotNull, @NotEmpty and @NotBlank.

Answer : The @NotNull is used for CharSequence, Collection, Map or Array object cannot be null, however can be empty. The @NotEmpty is used for the CharSequence, Collection, Map or Array object cannot be null and not empty (size > 0). The @NotBlank is used for the string is not null and the length is greater than zero.

61. What is JPA and how is Hibernate associated to JPA?

Answer : Java Persistence API is a specification of how object relational mapping is supposed to be done. Java is an OOP language. Data from objects needs to be stored in relational tables made using SQL. JPA defines the interface of how the mapping should be done. JPA is just a specification with no implementation.

Hibernate is an implementation of the JPA specification which implements all annotations specified by JPA. The main benefit of using JPA is that in the future, the implementation can be switched.

62. How does Hibernate help a programmer?

Answer : Java is an OOP language. Data from objects needs to be stored in relational tables made using SQL. Hibernate provides an alternative way of storing data from Java objects into a relational database.

63. Explain high level architecture of the Hibernate framework.

Answer : The Session Factory is a cache of compiled mappings for a single database. It represents any conversation between the Java application and the persistent store. It is a wrapper used for JDBC. JavaBeans/POJOs also provide the option of persistent objects with the persistent state and business function associated with one org.hibernate. The Session Transaction is used by Java application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction.

64. Provide example of an Entity mapping with Hibernate.

Answer : The following piece of code should do the work:

@Entity

@Table(name=”TBL_PERSON”,

           uniqueConstraints=

           @UniqueConstraint(

               name=”person_id”,

               columnNames={“name”, “person_id”} ) )

public class Person implements Serializable {

    @Column(name=”name”)

    public String getName() { return name; }

    @Column(name=”person_id”)

    public String getId() { return id; }

}

65. How to indicate in Hibernate that a table will not be updated using the application?

Answer : In Hibernate, generally there exist tables which are not updated by using it directly. Typical examples would be master data tables containing list of Countries or States. We can use the @Immutable annotation to indicate in Hibernate that a table will not be updated from the application. This allows Hibernate to make some minor performance optimizations.

66. How can a unique identifier be generated using Hibernate?

Answer : Hibernate can create identifier values automatically. There are several identifier generation strategies.

  • SEQUENCE uses a named database sequence to generate identifiers.
  • CUSTOM GENERATOR helps to write own logic.
  • AUTO selects any one of the above based on the database.
    • IDENTITY supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HSQL

67. What is optimistic locking? How can you use it with Hibernate?

Answer : In applications which have long running transactions, optimistic locking provides required scalability. Without optimistic locking, the tables get locked and avoid concurrent access. Hibernate provides two approaches to achieve optimistic locking: version number or timestamp. The former is preferred and is implemented using @Version annotation. Entity manager uses the LOCKING_COLUMN to detect conflicting updates.

68. How do you implement single table per class hierarchy strategy in Hibernate?

Answer : The following example shows how to configure single table per class hierarchy strategy using Annotations in Hibernate. Observe carefully:

       @Entity@Inheritance(strategy=InheritanceType.SINGLE_TABLE)@DiscriminatorColumn(    name=”cartype”,    discriminatorType=DiscriminatorType.STRING)@DiscriminatorValue(“Car”)public class Car { … }@Entity@DiscriminatorValue(“Formula1”)public class FormulaOneCar extends Car { … }

69. How to implement table per class strategy in Hibernate?

Answer : Table per class strategy is the default strategy for Hibernate. It can be declared explicitly using annotations in the following way:

       @Entity@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)public class Car implements Serializable { … }@Entity@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)public class FormulaOneCar implements Serializable { … }

70. How to specify a one to many unidirectional relationship in Hibernate?

Answer : The provided example shows how to implement a one to many unidirectional relationship using Annotations. The key annotation is @OneToMany.

           public class Parent {    @Id    @GeneratedValue    private long id;@OneToMany private Set<Child> children;}public class Child {   @Id   @GeneratedValue private long id;private String name;}

71. How to specify a one-to-many bidirectional relationship in Hibernate?

Answer :  The given example shows how to make a one to many relationship bidirectional. In addition to the unidirectional @OneToMany annotation, we need to specify @ManyToOne annotation for the parent attribute in Child class.

             public class Parent {    @Id    @GeneratedValue    private long id;     @OneToMany    private Set<Child> children;}public class Child {   @Id   @GeneratedValue   private long id;   private String name;      @ManyToOne   private Parent parent;}

72. How to implement pagination in Hibernate?

Answer : The First Result and the Maximum No of Rows that needs to be returned from a query can be specified. Follow the given example to understand better:

           Query q = sess.createQuery(“Some HQL Query”);q.setFirstResult(50); //50th row would be the first result returnedq.setMaxResults(100); //100 is the maximum number of rows returnedList cats = q.list();

73. What is meant by a lazy association?

Answer : Consider a Parent table associated with a corresponding Child table. When the Parent table is loaded, should the content of the Child table also be loaded?

In lazy association, the Child relationship is loaded when it is needed. This is the default configuration in Hibernate.

74. What is ‘N + 1 Selects’ Problem in Hibernate?

Answer : The default join in Hibernate is the select join. In a Parent – Child relationship with the Parent having N children, using select join, Hibernate executes N + 1 queries to retrieve all the details of Parent and all of the Children’s. This is known as the ‘N + 1 Selects’ problem in Hibernate.

75. How to achieve automatic schema generation from Hibernate Mappings?

Answer : SQL DDL can be generated from mapping files by using the Schema Export tool that is inbuilt in Hibernate. It must be ensured that the mapping files provide detailed constraints like not null, maximum length, unique keys, foreign keys so that the generated schema generated has appropriate relationships and constraints. It also has the feature to generate incremental updates. The command used to run the SchemaExport is:

     java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files 

76. What is the use of the Schema Validator?

Answer : The Schema Validator tool is used to verify whether the mapping configured “matches” the existing database structure.

77.Explain lazy fetching in Hibernate.

Answer : Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object .But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. 

78.Differentiate between session.save() , session.saveOrUpdate() and session.persist().

Answer : The session.save() method saves does an insert and will fail if the primary key is already persistent.  The session.saveOrUpdate() method does a select first to determine if it needs to do an insert or an update. Data is inserted if primary key does not exist otherwise data is updated. The session.persist() method has the same function as the session.save() method.
But the session.save() method returns serializable object but the session.persist() method returns void. The session.save() method returns the generated identifier (Serializable object) but the session.persist() method doesn’t. 

79.How to Integrate Struts Spring in Hibernate?

Answer : The following steps need to be followed to integrate Struts Spring in Hibernate:

Step 1. Add the config.xml add plugin in the struts.

Step 2. Configure datasourse in the applicationContext.xml file.
Step 3. Configure the SessionFactory.

Step 4. Configure the User.hbm.xml.

Step 5. In the applicationContext.xml, configure for DAO.
Step 6. Use the DAO Class. 

80.How to prevent slate object updating in Hibernate?

Answer : The concept of version checking is used in Hibernate when more than one thread tries to access the same data. In Hibernate, slate object updating can be prevented by using version checking. Check the version of the row where the updating is taking place. Get the version of the row when the row of the TABLE is fetched for update. At the time of updating, the version number is fetched and matched with the version number fetched at the time of fetching. 

81.What is version checking in Hibernate?

Answer : The concept of version checking is used in Hibernate when more than one thread tries to access the same data. 
For example:
User A edits the row of the TABLE for update and in the same time User B edits the same record for update and clicks the update. Then User A clicks the Update and the update is completed. Change made by user A is retained.

82.Explain the saveOrUpdate() method.

Answer : The saveOrUpdate() method performs the following:

  • If another object associated with the session has the same identifier, it throws an exception.
  • If the object has no identifier property, the method save() is applied to it.
  •  If the object’s identifier has the value assigned to a newly instantiated object, the method save() is applied to it.
  • If the object is versioned (by a < version > or < timestamp>), and the version property value is the same, the value assigned to a newly instantiated object, the method save() is applied to it otherwise the method update() is applied on the object.

83.Explain the saveOrUpdate() method.

Answer : The merge() method performs the following functions:

  • If there is a persistent instance with the same identifier currently associated with the session, it copies the state of the given object onto the persistent instance.
  • If there is no persistent instance currently associated with the session, it loads it from the database, or creates a new persistent instance.
  • If the persistent instance is returned, the given instance does not become associated with the session, it remains detached.

84.Differentiate between session.load() and session.get() methods.

Answer : The load() method throws an unrecoverable exception if there is no matching database row. The get() method returns null if there is no matching database row. 

Cat fritz = (Cat) session.load(Cat.class, “1”); 

This command returns the Cat Object with key 1. If there is no Cat Object with key 1 then throw will throw an unrecoverable exception. 

If the class is mapped with a proxy, the load() method just returns an uninitialized proxy and does not hit the database until a method of the proxy is invoked. This behaviour is very useful if an association has to be created to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if the batch size is defined for the class mapping. 

Cat fritz = (Cat) session.get(Cat.class, “1”); 

85.Differentiate between the Equal and Not Equal criteria query.

Answer : The following piece of code can easily represent the difference between the equal and not equal methods:

< class name=”com.bean.Organization” table=”ORGANIZATION” >< id name=”orgId” column=”ORG_ID” type=”long” >< generator class=”native”/ >< / id >< property name=”organizationName” column=”ORGANISATION_NAME” type=”string” length=”500″/ >< property name=”town” column=”TOWN” type=”string” length=”200″/ >< / class >

86.How does Value replacement in Message Resource Bundle actually work?

Answer : Follow the piece of code to understand the complete process:

        errors.required={0} is required.ActionErrors errors = new ActionErrors();errors.add(ActionErrors.GLOBAL_ERROR,new ActionError(“error.custform”,”First Name”));

‘First Name is required’ is the first error that appears after execution of the code.

87.How to delete persistence objects? 

Answer : The Session.delete() method removes an object’s state from the database. The application might still hold a reference to a deleted object. It’s best to think of the delete() method as making it a persistent instance such as the transient.sess.delete(cat).

88.How to set 2nd level cache in Hibernate with the EHCache?

Answer : The following piece of code needs to be executed in order to set second level cache in Hibernate with the EHCache:

String ecache = appHome+File.separatorChar+”ehcache.xml”;try {CacheManager.create(ecache);} catch (CacheException e){// logger.logError(e);}*///ThensessionFactory = configuration.buildSessionFactory();//ECache.xml is likemaxElementsInMemory=”10000″eternal=”false”timeToIdleSeconds=”120″timeToLiveSeconds=”120″overflowToDisk=”true”diskPersistent=”false”diskExpiryThreadIntervalSeconds=”120″/>maxElementsInMemory=”300″eternal=”false”overflowToDisk=”false”/>

89.How to get Hibernate statistics?

Answer : Execute the following piece of code in order to get Hibernate statistics: SessionFactory.getStatistics().

90.Explain Criteria Query Two Condition.

Answer : The following piece of code is used to execute the Criteria Query Two Condition:

       < class name=”com.bean.Organization” table=”ORGANIZATION” >< id name=”orgId” column=”ORG_ID” type=”long” >< generator class=”native”/ >< / id >< property name=”organizationName” column=”ORGANISATION_NAME” type=”string” length=”500″/ >< property name=”town” column=”TOWN” type=”string” length=”200″/ >< property name=”statusCode” column=”STATUS” type=”string” length=”1″/ >< / class >

91.What are the general considerations for defining the Hibernate persistent classes?

Answer : These are the general considerations for defining the Hibernate persistent classes:

1.There must be a default no-argument constructor for the persistent classes and there should be a getXXX()and setXXX methods for all the persistent instance variables. 

2. The equals() and hashCode() methods must be implemented based on the business key and it is important not to use the id field in the equals() and hashCode() definition if the id field is a surrogate key. This is because Hibernate only generates and sets the field when saving the object. 

3. It is recommended to implement the Serializable interface. This is potentially useful if migration around a multi-processor cluster is required. 

4. The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

92.Mention the SQL statements execution order.

Answer : This is the usual execution order of SQL statements:

All entity insertions are executed in the same order the corresponding objects were saved using Session.save() method.
2. All entity updates are executed next.
3. All collection deletions. 
4. All collection element deletions, updates and insertions. 
5. All collection insertions. 
6. All entity deletions are executed in the same order the corresponding objects were deleted using Session.delete() method.

93.Differentiate between the list() and iterate() methods in Hibernate.

Answer : If instances are already in the session or second-level cache, the iterate() method will give better performance. If they are not already cached, the iterate() method will be slower. The list() method requires many database hits for a simple query.

94.How to represent SQL Queries in Hibernate?

Answer : A query in SQL can be created using createSQLQuery() and let Hibernate take care of the mapping from result sets to objects. The session.connection() method can be called at any time and use the JDBC Connection directly. SQL queries can contain named and positional parameters just like Hibernate queries. If the Hibernate API is used, enclose SQL aliases in braces. Follow the example:

       List cats = session.createSQLQuery(“SELECT {cat.*} FROM CAT {cat} WHERE ROWNUM<10″,”cat”,Cat.class).list();List cats = session.createSQLQuery(“SELECT {cat}.ID AS {cat.id}, {cat}.SEX AS {cat.sex}, ” +”{cat}.MATE AS {cat.mate}, {cat}.SUBCLASS AS {cat.class}, … ” +”FROM CAT {cat} WHERE ROWNUM<10″,”cat”,Cat.class).list()

95.How to use the addScalar() method in Hibernate?

Answer : The addScalar() method in the given example confirms that the maxWeight is always double type. 

Double max = (Double) sess.createSQLQuery(“select max(cat.weight) as maxWeight from cats cat”) .addScalar(“maxWeight”, Hibernate.DOUBLE); .uniqueResult(); 

96.Mention the code for modifying persistent objects.

Answer : Follow the given code:

SQLQuery sq = (SQLQuery) session.getNamedQuery(“selectAllEmployees_SP”);List results = sq.list();

97.How to create a primary key using Hibernate?

Answer : The following code is used to generate a Primary Key in Hibernate:

< id name=”userId” column=”USER_ID” type=”int” > < generator class=”increment” />

98.What are concurrency strategies?

Answer : A concurrency strategy is a mediator which is responsible for storing data in the cache and retrieve them from the cache. If a second-level cache is enabled, for each persistent class and collection, it needs to be decided which cache concurrency strategy must be used.

  • Transactional− This strategy is used for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update.
  • Read-write− This strategy is also used for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update.
  • Non Strict-read-write− This strategy makes no guarantee of consistency between the cache and the database. This strategy is used if data hardly ever changes and a small likelihood of stale data is not of critical concern.
  • Read-only– This is a concurrency strategy suitable for data which never changes and is used for reference data only.

99.What is Query level cache in Hibernate?

Answer : Hibernate implements a cache for query resultsets that integrates closely with the second-level cache. It is an optional feature and requires two additional physical cache regions that holds the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.

100.What is second level cache in Hibernate?

Answer : The second level cache is an optional cache and the first-level cache will always be referred to before any attempt is made to locate an object in the second-level cache. The second-level cache can be organized on a per-class and per-collection basis and is mainly responsible for caching the objects across sessions.

101.Explain first level cache in Hibernate.

Answer : The Session object keeps an object under its own power before committing it to the database. The first-level cache is the Session cache and is a mandatory cache through which all requests must pass.

102.Explain HQL.

Answer : HQL or Hibernate Query Language takes Java objects in the same way as SQL takes tables. HQL is an Object Oriented Query language and is independent of databases.

103.What is lazy loading?

Answer : Lazy loading is a technique in which objects are loaded on basis of demand. Lazy loading has been made default since the third version of Hibernate. This has been done in order to ensure that child objects are not loaded when the parent is loaded.

104.What is the difference between save() and persist() methods of session object?

Answer : The session.save() method saves the object and returns the id of the instance whereas the session.persist() method does not return anything after saving the instance.

105.Is Session a thread-safe object?

Answer :  A Session object is not thread-safe.

106.Is SessionFactory a Thread-safe object?

Answer : A SessionFactory object is thread-safe and can be accessed by multiple threads simultaneously.

107.What is many-to-many association?

Answer : A Many-to-Many mapping can be implemented by using a Set java collection that does not contain any duplicate element.

The <many-to-many> element indicates that one object relates to many other objects and other column attributes are used to link intermediate columns.

108.What is one-to-many association?

Answer : In the One-to-Many mapping association, an object can be associated with multiple objects. A One-to-Many mapping can be implemented by using a Set Java collection that does not contain any duplicate element. The <one-to-many> element of a set element indicates that one object relates to many other objects.

109.What is one-to-one association?

Answer : A one-to-one association is similar to a many-to-one association with a difference that the column will be set as unique. A <many-to-one> element is used to define a one-to-one association.

The name attribute is set to the defined variable in the parent class, while the column attribute is used to set the column name in the parent table which is set to unique so that only one object can be associated with another object.

110. What is many-to-one association?

Answer : A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. A <many-to-one> element is used to define a many-to-one association. The name attribute is set to the defined variable in the parent class. The column attribute is used to set the column name in the parent table.

111. Which element of the hbm.xml is used to map a java.util.SortedMap property in Hibernate?

Answer : The <map> element of the hbm.xml is used for the given operation and is initialized with the java.util.TreeMap. The sort attribute can be set to either a comparator or natural ordering.

112. Which element of the hbm.xml is used to map a java.util.Map property in Hibernate?

Answer : The <map> element of the hbm.xml is used for the given operation and is initialized with the java.util.HashMap.

113. Which element of the hbm.xml is used to map a java.util.Map property in Hibernate?

Answer : The <map> element of the hbm.xml is used for the given operation and is initialized with the java.util.HashMap.

114. Which element of the hbm.xml is used to map a java.util.Collection property in Hibernate?

Answer : The <bag> or <ibag> element of the hbm.xml is used for the given operation and is initialized with the java.util.ArrayList.

115. Which element of the hbm.xml is used to map a java.util.List property in Hibernate?

Answer : The <list> element of the hbm.xml is used for the given operation and is initialized with the java.util.ArrayList.

116. Which element of the hbm.xml is used to map a java.util.SortedSet property in Hibernate?

Answer : The <set> element of the hbm.xml is used for the given operation and is initialized with the java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering.

117. Which element of the hbm.xml is used to map a java.util.Set property in Hibernate?

Answer : The <set> element of the hbm.xml is used for the given operation and is initialized with java.util.HashSet.

118. Which element of the hbm.xml is used to map a Java class property to a column in the database table?

Answer : The <property> element is used to map a Java class property to a column in the database table.

  • The nameattribute of the element refers to the property in the class.
  • The columnattribute refers to the column in the database table.
  • The typeattribute holds the Hibernate mapping type, this mapping types will convert from Java to SQL data type.

119. Which element of the hbm.xml is used to automatically generate the primary key values?

Answer : The <generator> element within the id element is used to automatically generate the primary key values. The class attribute of the generator element is set to native and allows Hibernate to pick up either the identity, the sequence or the hilo algorithm to create a primary key depending upon the capabilities of the underlying database.

120. Which element of the hbm.xml maps the unique ID attribute in class to the primary key of the database table?

Answer : The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the Hibernate mapping type and helps to convert from Java to SQL data type.

121. Which element of the hbm.xml defines a specific mapping from a Java classes to the database tables?

Answer : The <class> elements are used to describe specific mappings from a Java classes to the database tables. The Java class name is stated using the name attribute of the class element and the database table name is stated using the table attribute.

122. What is the root node of the hbm.xml?

Answer : The mapping document is an XML document which has the <hibernate-mapping>as the root element and comprises all the <class> elements.

123. Where are the Object/relational mappings defined in Hibernate?

Answer : An Object/relational mappings are usually defined in an XML document. The same mapping file instructs Hibernate on the process of mapping the defined class or classes to the database tables. The mapping document in a file with the format <classname>.hbm.xml must be saved.

124. What are the best practices recommended by Hibernate for persistent classes?

Answer : The following rules must be followed while defining a persistent classes:

  • All Java classes required to be persisted need a default constructor.
  • All classes must compulsorily contain an ID in order to allow the easy identification of objects within Hibernate and the database. This property maps to the primary key column of a database table.
  • All attributes that are supposed to be persisted should be declared private and have the getXXX()and setXXX() methods defined in the JavaBean style.
  • A central feature of Hibernate proxies depends upon the persistent class being non-final or the implementation of an interface that declares all public methods.

125. What are persistent classes in Hibernate?

Answer : The Java classes whose objects or instances are stored in database tables are called persistent classes in Hibernate.

126. Which method is used to save or update the state of the given instance from the underlying database?

Answer : The Session.saveOrUpdate() method either saves or updates the objects of the given instance.

127. Which method is used to update the state of the given instance from the underlying database?

Answer : The Session.update() method updates the state of the given instance from the underlying database.

128. Which method is used to save the state of the given instance from the underlying database?

Answer : The Session.save() method saves the state of the given instance from the underlying database.

129. Which method is used to re-read the state of the given instance from the underlying database?

Answer : The Session.refresh() method re-reads the state of the given instance from the underlying database.

130. Which method is used to get a persistent instance from the datastore?

Answer : The Session.get() method returns the persistent instance of the given named entity with the given identifier or null if there is no such persistent instance.

131. Which method is used to remove a persistent instance from the data store?

Answer : The Session.delete() method removes a persistent instance from the data store.

132. Which method is used to create a SQL query?

Answer : The Session.createSQLQuery() creates a new instance of SQL Query for the given SQL query string.

133. Which method is used to create a HQL query?

Answer : The Session.createQuery() method creates a new instance of Query for the given HQL query string.

134. Which method is used to add a criteria to a Query?

Answer : The Session.createCriteria() method creates a new Criteria instance, for the given entity class or a superclass of an entity class.

135. What is the purpose of the Session.beginTransaction() method?

Answer : The Session.beginTransaction() method begins a unit of work and returns the associated Transaction object.

136. What are the three states of a persistent entity at a given point in time?

Answer : Instances in Hibernate exist in one of the following three states at a given point in time −

  • Transient− A new instance of any persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate.
  • Persistent− A transient instance can be made persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.
  • Detached− When the Hibernate Session is closed, the persistent instance becomes a detached instance.

137. What is a dialect?

Answer : A dialect is a set of code files or a single file seldom that defines the procedure of connecting database to a Java class. A dialect in Hibernate plays the role of understanding the communication taking place with the underlying database. Whenever the original database changes, the dialect and database credentials need to be changed in the Hibernate configuration.

138. Explain the possible ways of configuring Hibernate framework.

Answer : The Hibernate framework can be configured using both XML and Java class annotations. The Java class based annotation feature was introduced only from Hibernate 4.0. Hence, any lower version supports only XML based configuration.

139. Explain the concept of a connection pool.

Answer : Hibernate framework ensures that new connections are established until the defined maximum limit is reached. Post the limit, Hibernate reuses the database connection object. In an enterprise application, the application will be constantly hit by numerous users. If the application server creates a new connection for every request, it becomes a weight on the database server. However, if there is a single database connection only, there will be a huge overhead of requests for query. Hence, it is preferred to have an inadequate number of database connections pre-configured in Hibernate. Thus, the Hibernate connection pool is a bunch of Database connection objects created for managing parallel communication with the database.

140. Does the JPA help in Hibernate framework?

Answer : Hibernate was the first application to use XML mapping to strict bind the Hibernate Value objects to Database objects. This mapping was based on XML and susceptible to to high errors and required more effort in configuring the mapping. With JPA, Hibernate simplified the process of mapping by enabling the scanning for JPA annotations. These annotations remove the need to use XML for the mapping.

141. Mention the configurations involved in any kind of Hibernate framework.

Answer : Any Hibernate framework is an enormous framework designed to handle every database operation for you. Hibernate has default values for almost every non-database configuration like the Connection pool size, caching levels, table creation mode, etc. Thus, despite having so many configurable features, it allows to get started with minimal configuration. The following list involves the possible configurations in any Hibernate framework:

  • Database URL
  • ORM mapping
  • Table creation mode – Create/Update
  • Database credentials
  • Database dialect
  • Caching levels
  • Connection pool configuration

142. Explain the creation of a database connection in Hibernate.

Answer : The following steps are used for the creation of a database connection:

  • Hibernate reads the configured dialect to decide the driver jar to be used.
  • Hibernate comes pre-packaged with the database driver jars. These jars are similar to the ones used for connecting to a database using JDBC.
  • Based on the dialect, Hibernate dynamically registers the respective driver class and uses the URL and credentials to connect to the database using JDBC in the backend.

143. List out the various ways an object-table map is configured.

Answer : There are two possible ways to configure the mapping in Hibernate.

  • Create an XML file defines the mapping between the database column and the class variable, known as mapping XML. An entry of every such XML needs to be done in the hibernate.cfg.xml in order to ensure that Hibernate recognizes and precompiles these bindings.
  • The other way to configure a bean is to use annotated Java class for the mapping. Annotated Java classes are automatically scanned for as long as the path of the folder is specified in the hibernate.cfg.xml.

144. How to specify a table name linked to an entity using an annotation?

Answer : The annotation @Table is used to state the database table name linked to the entity. This entity requires a mandatory attribute, the name which specifies the table name as in the database.

145. Mention a way using which a variable in an entity connect to the database column.

Answer : The annotation @Column is used to define a column name associated with a variable. In absence of this annotation, Hibernate precompiles the mapping of variable mapped to the column with the same name. The attribute known as the name is a compulsory attribute to specify the column name different from the variable name.

146. How do we configure a connection pool size?

Answer : The connection pool size in Hibernate has two values –

  • Minimum pool size
  • Maximum pool size.

147. Why is the Session.beginTransaction() used?

Answer : In Hibernate, every interchange of data is preserved using a transaction. Whenever a new data exchange is to be started, the function Session.beginTransaction() is called to start the transaction.

148. How to complete a transaction in Hibernate?

Answer : Two actions can be carried out to complete a transaction in Hibernate:

  • Commit
  • Rollback

Whenever a transaction is committed, the data interchange is written to the database. In case of a rollback, the transaction data is flushed and never written or updated to the database.

149. Mention the annotations that are used to define a mapping in Java files.

Answer : In order to define mapping in Java files, there are three altered annotations that can be used as needed:

  • @OneToOne
  • @ManyToOne
  • @ManyToOne

The usage of the annotations is quite clear. The annotation requires a mandatory attribute known as MappedBy to identify the related table.

150. Is Polymorphism supported by Hibernate?

Answer : Hibernate classes mainly support its operations via polymorphism itself and hence, Hibernate inherently supports polymorphism.

 

Conclusion:

Hibernate has been generating constant demand for the past few years and expected to continue as there are more Java technology based projects in pipeline. We believe, the above selected 150 Hibernate interview questions will help you in Job interview.

Kiara is a career consultant focused on helping professionals get into job positions in the tech industry. She is also a skilled copywriter who has created well-crafted content for a wide range of online publications in the career and education industry.