Hibernate Interview Questions and Answers
Hibernate is one of the most widely used ORM tools for Java applications. It’s used a lot in enterprise applications for database operations. So I decided to write a post about interview questions to brush up your knowledge before the interview. Whether you are fresher or experienced, having good knowledge of Hibernate ORM tool helps in cracking interviews. Here I am providing important hibernate interview questions with answers to help you brush up your knowledge and impress your interviewer. Just like other interview questions posts, chances are that I will be adding more questions to this list in the future, so you might want to bookmark it for future reference.
Interview Questions
What is Hibernate Framework?
Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is a Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides a reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provides the option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML-based configuration. Similarly, hibernate configurations are flexible and can be done from XML configuration files as well as programmatically.
What is Java Persistence API (JPA)?
Java Persistence API (JPA) provides a specification for managing the relational data in applications. The current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013. JPA specifications are defined with annotations in the javax.persistence package. Using JPA annotations helps us in writing implementation-independent code.
What are the important benefits of using Hibernate Framework?
Some of the important benefits of using Hibernate framework are:
- Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
- Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
- Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism, and association.
- Hibernate is an open-source project from the Red Hat Community and is used worldwide. This makes it a better choice than others because the learning curve is small and there is tons of online documentation, and help is easily available in forums.
- Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating Hibernate with Spring applications.
- Hibernate supports lazy initialization using proxy objects and performs actual database queries only when it’s required.
- Hibernate cache helps us in getting better performance.
- For database vendor-specific features, Hibernate is suitable because we can also execute native SQL queries. Overall Hibernate is the best choice in the current market for ORM tools, it contains all the features that you will ever need in an ORM tool.
What are the advantages of Hibernate over JDBC?
Some of the important advantages of Hibernate framework over JDBC are:
- Hibernate removes a lot of boiler-plate code that comes with the JDBC API, and the code looks cleaner and more readable.
- Hibernate supports inheritance, associations, and collections. These features are not present with the JDBC API.
- Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside transactions. In the JDBC API, we need to write code for transaction management using commit and rollback. Read more at JDBC Transaction Management.
- JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the time it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throws JDBCException or HibernateException unchecked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
- Hibernate Query Language (HQL) is more object-oriented and close to the Java programming language. For JDBC, we need to write native SQL queries.
- Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
- Hibernate provides the option through which we can create database tables too, for JDBC tables must exist in the database.
- Hibernate configuration helps us in using JDBC-like connection as well as JNDI DataSource for connection pool. This is a very important feature in enterprise applications and is completely missing in JDBC API.
- Hibernate supports JPA annotations, so the code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
Name some important interfaces of Hibernate framework?
Some of the important interfaces of Hibernate framework are:
1. **SessionFactory (org.hibernate.SessionFactory)**: SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
2. **Session (org.hibernate.Session)**: Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC `java.sql.Connection` and works as a factory for `org.hibernate.Transaction`. We should open session only when it's required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.
3. **Transaction (org.hibernate.Transaction)**: Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
What is hibernate configuration file?
Hibernate configuration file contains database-specific configurations and is used to initialize SessionFactory. We provide database credentials or JNDI resource information in the Hibernate configuration XML file. Some other important parts of the Hibernate configuration file are Dialect information so that Hibernate knows the database type and mapping file or class details.
What is hibernate mapping file?
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping files come in handy when we are using third-party classes and we can’t use annotations.
Name some important annotations used for mapping?
Hibernate supports JPA annotations, and it has some other annotations in the org.hibernate.annotations
package. Some of the important JPA and Hibernate annotations used are:
- javax.persistence.Entity: Used to declare a class as an entity bean.
- javax.persistence.Table: Used to specify the table name in the database that corresponds to the entity bean.
- javax.persistence.Access: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
- javax.persistence.Column: Specifies the column in the database table that maps to a field or property in the entity bean.
- javax.persistence.Id: Denotes the primary key of the entity bean.
- javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
- javax.persistence.GeneratedValue: Specifies the generation strategy for the primary key, used in conjunction with
javax.persistence.GenerationType
. - javax.persistence.OneToOne: Defines a one-to-one relationship between two entity beans.
- javax.persistence.OneToMany: Defines a one-to-many relationship between two entity beans.
- javax.persistence.ManyToOne: Defines a many-to-one relationship between two entity beans.
- javax.persistence.ManyToMany: Defines a many-to-many relationship between two entity beans.
- org.hibernate.annotations.Cascade: Used to define cascade behavior for operations such as save, update, delete, etc.
- avax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with `org.hibernate.annotations.GenericGenerator` and `org.hibernate.annotations.Parameter`
package com.journaldev.hibernate.model;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
@Entity
@Table(name = "EMPLOYEE")
@Access(value=AccessType.FIELD)
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "emp_id")
private long id;
@Column(name = "emp_name")
private String name;
@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
//getter setter methods
}
package com.journaldev.hibernate.model;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
@Table(name = "ADDRESS")
@Access(value=AccessType.FIELD)
public class Address {
@Id
@Column(name = "emp_id", unique = true, nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
private long id;
@Column(name = "address_line1")
private String addressLine1;
@OneToOne
@PrimaryKeyJoinColumn
private Employee employee;
//getter setter methods
}
What is Hibernate SessionFactory and how to configure it?
SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible for reading the Hibernate configuration parameters, connecting to the database, and providing Session objects. Usually, an application has a single SessionFactory instance, and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created, this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. SessionFactory also provides methods to get the Class metadata and Statistics instance to get the stats of query executions, second-level cache details, etc.
Hibernate SessionFactory is thread safe?
Internal state of SessionFactory is immutable, so it’s thread-safe. Multiple threads can access it simultaneously to get Session instances.
What is Hibernate Session and how to get it?
Hibernate Session is the interface between the Java application layer and Hibernate. This is the core interface used to perform database operations. The lifecycle of a session is bound by the beginning and end of a transaction. Session provides methods to perform create, read, update, and delete operations for a persistent object. We can execute HQL queries, SQL native queries, and create criteria using the Session object.
Are the Sessions thread safe?
Hibernate Session object is not thread-safe, and every thread should get its own session instance and close it after its work is finished.
What is difference between openSession and getCurrentSession?
Hibernate SessionFactory getCurrentSession()
method returns the session bound to the context. But for this to work, 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.
<property name="hibernate.current_session_context_class">thread</property>
Hibernate SessionFactory openSession()
method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in a multi-threaded environment. There is another method openStatelessSession()
that returns a stateless session.
What is difference between Hibernate Session get() and load() method?
Hibernate session comes with different methods to load data from the database. get()
and load()
are the most used methods. At first look, they seem similar but there are some differences between them:
get()
loads the data as soon as it’s called, whereasload()
returns a proxy object and loads data only when it’s actually required, soload()
is better because it supports lazy loading.- Since
load()
throws an exception when data is not found, we should use it only when we know data exists. - We should use
get()
when we want to make sure data exists in the database.
What is Hibernate caching and first level cache?
As the name suggests, Hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application. Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. 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 not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
How to configure Second Level Cache using EHCache?
EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.
- Add hibernate-ehcache dependency in your maven project, if it's not maven then add corresponding jars.
```
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.5.Final</version>
</dependency>
```
- Add below properties in hibernate configuration file.
```
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- For singleton factory -->
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
-->
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
```
- Create EHCache configuration file, a sample file myehcache.xml would look like below.
```
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir/ehcache" />
<defaultCache maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="employee" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="5" timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
```
- Annotate entity beans with @Cache annotation and caching strategy to use. For example,
```
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "ADDRESS")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {
}
```
That's it, we are done. Hibernate will use the EHCache for second level caching, read [Hibernate EHCache Example](/community/tutorials/hibernate-ehcache-hibernate-second-level-cache) for a complete example with explanation.
What are different states of an entity bean?
An entity bean instance can exist in one of three states:
- Transient: The entity is not associated with any session or database record. It exists only in memory.
- Persistent: The entity is associated with a session and corresponds to a record in the database.
- Detached: The entity was previously in a persistent state but is no longer associated with any session.
What is use of Hibernate Session merge() call?
Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked.
What is difference between Hibernate save(), saveOrUpdate(), and persist() methods?
Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately. Hibernate persist is similar to save with transaction. I feel it’s better than save because we can’t use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn’t return the generated id immediately, so data persistence happens when needed. Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed.
What will happen if we don’t have no-args constructor in Entity bean?
Hibernate uses the Reflection API to instantiate entity beans. Specifically, it requires a no-args constructor to create an instance of the entity. If a no-args constructor is missing, Hibernate will throw a HibernateException
when attempting to instantiate the entity.
What is difference between sorted collection and ordered collection, and which one is better?
When we use Collection API sorting algorithms to sort a collection, it’s called sorted list. For small collections, it’s not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement `Comparable` or `Comparator` interface for it to work, read more at [java object list sorting](/community/tutorials/comparable-and-comparator-in-java-example). If we are using Hibernate framework to load collection data from database, we can use it’s Criteria API to use “order by” clause to get ordered list. Below code snippet shows you how to get it.
List empList = session.createCriteria(Employee.class)
.addOrder(Order.desc("id")).list();
Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn’t cause memory issues.
What are the collection types in Hibernate?
There are five collection types used for one-to-many relationship mappings.
1. Bag
2. Set
3. List
4. Array
5. Map
How to implement Joins in Hibernate?
Joins in Hibernate can be implemented in the following ways:
- Using HQL with the
JOIN
keyword. For example:FROM Employee e JOIN e.department d WHERE d.name = 'HR'
. - Using criteria queries and the
createAlias()
method to define joins programmatically. - Using native SQL queries with the
addEntity()
method to map the results to entities.
Why we should not make Entity Class final?
Hibernate uses proxy classes for features like lazy loading. These proxy classes extend the original entity class. If an entity class is declared as final
, Hibernate cannot create proxies, which disables lazy loading and can lead to reduced performance or runtime errors.
What is HQL and what are its benefits?
Hibernate Query Language (HQL) is an object-oriented query language provided by Hibernate. It is similar to SQL but operates on Hibernate entities rather than database tables. HQL supports polymorphism, inheritance, and associations, making it more powerful and easier to use in object-oriented applications.
Benefits of HQL:
- It is database-independent, as queries are written in terms of the entity model rather than the database schema.
- Supports object-oriented concepts such as inheritance and polymorphism.
- Provides better readability and maintainability compared to native SQL.
What is Query Cache in Hibernate?
Query cache is a caching mechanism in Hibernate that caches the results of HQL queries. It works in conjunction with the second-level cache and is useful for queries that are executed frequently with the same parameters. Query cache can be enabled by adding the following property to the Hibernate configuration file:
<property name="hibernate.cache.use_query_cache">true</property>
In code, you can enable query caching for a specific query as follows:
Query query = session.createQuery("from Employee");
query.setCacheable(true);
Can we execute native SQL query in Hibernate?
Yes, Hibernate allows the execution of native SQL queries using the createSQLQuery()
method. Native SQL queries are useful for executing database-specific operations that cannot be performed using HQL.
Example:
SQLQuery query = session.createSQLQuery("SELECT * FROM EMPLOYEE");
query.addEntity(Employee.class);
List employees = query.list();
What is the benefit of native SQL query support?
Native SQL queries allow developers to use database-specific features, such as query hints or proprietary SQL functions, that are not supported by HQL. This can be helpful for optimizing performance or implementing advanced database functionalities.
What is Named SQL Query?
Named SQL Queries are pre-defined queries that can be reused throughout the application. They are defined using the @NamedQuery
or @NamedNativeQuery
annotations or in the Hibernate mapping file.
What are the benefits of Named SQL Query?
- Centralizes query definitions, making them easier to manage and debug.
- Provides better performance as queries are pre-compiled at startup.
- Encourages reusability by defining commonly used queries in a single place.
What is the benefit of Hibernate Criteria API?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach. Some of the common usage of Criteria API are:
- Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
- Criteria API can be used with ProjectionList to fetch selected columns only.
- Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
- Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
- Criteria API provides addOrder() method that we can use for ordering the results.
How to log Hibernate generated SQL queries in log files?
We can set below property for hibernate configuration to log SQL queries.
```
true
```
However we should use it only in Development or Testing environment and turn it off in production environment.
What is Hibernate Proxy and how it helps in lazy loading?
Hibernate uses proxy objects to implement lazy loading. A proxy is a subclass of the actual entity class that overrides methods to fetch data only when it is accessed. This improves performance by deferring database queries until the data is actually needed.
Lazy loading can be enabled using the fetch
attribute in mapping files or annotations:
@OneToMany(fetch = FetchType.LAZY)
private List
addresses;
How to implement relationships in Hibernate?
Relationships can be implemented using annotations or XML mappings. Common relationship types include:
- One-to-One: Use
@OneToOne
annotation withmappedBy
attribute for bidirectional mapping. - One-to-Many: Use
@OneToMany
annotation and a collection type likeList
. - Many-to-Many: Use
@ManyToMany
annotation with a join table.
How transaction management works in Hibernate?
Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session `beginTransaction()` to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction. Overall hibernate transaction management is better than JDBC transaction management because we don’t need to rely on exceptions for rollback. Any exception thrown by session methods automatically rollback the transaction.
What is cascading and what are different types of cascading?
When we have relationship between entities, then 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. Here is a simple example of applying cascading between primary and secondary entities.
```
import org.hibernate.annotations.Cascade;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
}
```
Note that Hibernate CascadeType enum constants are little bit different from JPA `javax.persistence.CascadeType`, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example. Commonly used cascading types as defined in CascadeType enum are:
1. None: No Cascading, it's not a type but when we don't define any cascading then no operations in parent affects the child.
2. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
3. SAVE\_UPDATE: Cascades save and update, available only in hibernate.
4. DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
5. DETATCH, MERGE, PERSIST, REFRESH and REMOVE - for similar operations
6. LOCK: Corresponds to the Hibernate native LOCK action.
7. REPLICATE: Corresponds to the Hibernate native REPLICATE action.
How to integrate log4j logging in Hibernate application?
Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps.
– Add log4j dependencies for maven project, if not maven then add corresponding jar files.
– Create log4j.xml configuration file or log4j.properties file and keep it in the classpath. You can keep file name whatever you want because we will load it in next step.
– For standalone projects, use static block to configure log4j using `DOMConfigurator` or `PropertyConfigurator`. For web applications, you can use ServletContextListener to configure it.
That’s it, our setup is ready. Create `org.apache.log4j.Logger` instance in the java classes and start logging.
How to use application server JNDI DataSource with Hibernate framework?
For web applications, it’s always best to allow servlet container to manage the connection pool. That’s why we define JNDI resource for DataSource and we can use it in the web application. It’s very easy to use in Hibernate, all we need is to remove all the database specific properties and use below property to provide the JNDI DataSource name.
<property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>
How to integrate Hibernate and Spring frameworks?
Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. The best part with using Spring is that it provides out-of-box integration support for Hibernate with **Spring ORM** module. Following steps are required to integrate Spring and Hibernate frameworks together.
1. Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.
2. Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
3. If you are using Hibernate 3, you need to configure `org.springframework.orm.hibernate3.LocalSessionFactoryBean` or `org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean` in Spring Bean configuration file. For Hibernate 4, there is single class `org.springframework.orm.hibernate4.LocalSessionFactoryBean` that should be configured.
4. Note that we don’t need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using `@Transactional` annotation.
What is HibernateTemplate class?
When Spring and Hibernate integration started, Spring ORM provided two helper classes – `HibernateDaoSupport` and `HibernateTemplate`. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management. However from Hibernate 3.0.1, we can use `SessionFactory` _getCurrentSession()_ method to get the current session and use it to get the spring transaction management benefits. If you go through above examples, you will see how easy it is and that’s why we should not use these classes anymore. One other benefit of `HibernateTemplate` was exception translation but that can be achieved easily by using `@Repository` annotation with service classes, shown in above spring mvc example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.
How to integrate Hibernate with Servlet or Struts2 web applications?
Hibernate integration with Servlet or Struts2 needs to be done using `ServletContextListener`.
Which design patterns are used in Hibernate framework?
Hibernate uses several design patterns to implement its functionality:
- Domain Model Pattern: Represents the application’s data and behavior as objects.
- Data Mapper Pattern: Maps domain objects to database tables and vice versa.
- Proxy Pattern: Used for lazy loading of associated objects.
- Factory Pattern: Used in the creation of
SessionFactory
.
What are best practices to follow with Hibernate framework?
Some of the best practices to follow in Hibernate are:
– Always check the primary key field access, if it’s generated at the database layer then you should not have a setter for this.
– By default hibernate set the field values directly, without using setters. So if you want hibernate to use setters, then make sure proper access is defined as `@Access(value=AccessType.PROPERTY)`.
– If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
– Use native sql query only when it can’t be done using HQL, such as using database specific feature.
– If you have to sort the collection, use ordered list rather than sorting it using Collection API.
– Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity specific query, you can keep them in the entity bean itself.
– For web applications, always try to use JNDI DataSource rather than configuring to create connection in hibernate.
– Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
– For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit of lazy loading.
– Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that in-memory state accurately represents the persistent state.
– Prefer DAO pattern for exposing the different methods that can be used with entity bean
– Prefer lazy fetching for associations
What is Hibernate Validator Framework?
Data validation is integral part of any application. You will find data validation at presentation layer with the use of Javascript, then at the server side code before processing it. Also data validation occurs before persisting it, to make sure it follows the correct format. Validation is a cross cutting task, so we should try to keep it apart from our business logic. That’s why JSR303 and JSR349 provides specification for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specs.
What is the benefit of Hibernate Tools Eclipse plugin?
Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or xml tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes before hand.
That’s all for the Interview Questions and Answers. I hope this helps you in preparing for your interviews!