Hibernate Interview Question & Answer
Hibernate Interview Question & Answer
Hibernate provides 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 provide 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
file as well as programmatically. For a quick overview of hibernate framework usage, you
can go through Hibernate Beginners Tutorial.
1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of
managing resources, so we can focus on business logic.
2. Hibernate framework provides support for XML as well as JPA annotations, that makes
our code implementation independent.
3. 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.
4. Hibernate is an open source project from Red Hat Community and used worldwide. This
makes it a better choice than others because learning curve is small and there are tons of
online documentations and help is easily available in forums.
5. 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.
6. Hibernate supports lazy initialization using proxy objects and perform actual database
queries only when it’s required.
7. Hibernate cache helps us in getting better performance.
8. For database vendor specific feature, hibernate is suitable because we can also execute
native sql queries.
Overall hibernate is the best choice in current market for ORM tool, it contains all the
features that you will ever need in an ORM tool.
1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks
more cleaner and readable.
2. Hibernate supports inheritance, associations and collections. These features are not
present with JDBC API.
3. Hibernate implicitly provides transaction management, in fact most of the queries can’t
be executed outside transaction. In JDBC API, we need to write code for transaction
management using commit and rollback. Read more at JDBC Transaction Management.
4. JDBC API throws SQLException that is a checked exception, so we need to write a
lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for
transaction management. Hibernate wraps JDBC exceptions and
throw JDBCException or HibernateException un-checked exception, so we
don’t need to write code to handle it. Hibernate built-in transaction management removes
the usage of try-catch blocks.
5. Hibernate Query Language (HQL) is more object oriented and close to java programming
language. For JDBC, we need to write native sql queries.
6. Hibernate supports caching that is better for performance, JDBC queries are not cached
hence performance is low.
7. Hibernate provide option through which we can create database tables too, for JDBC
tables must exist in the database.
8. Hibernate configuration helps us in using JDBC like connection as well as JNDI
DataSource for connection pool. This is very important feature in enterprise application
and completely missing in JDBC API.
9. Hibernate supports JPA annotations, so code is independent of implementation and
easily replaceable with other ORM tools. JDBC code is very tightly coupled with the
application.
5. Name some important interfaces of Hibernate framework?
Some of the important interfaces of Hibernate framework are:
1. SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutablethread-
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.
6. What is hibernate configuration file?
Hibernate configuration file contains database specific configurations and used to initialize
SessionFactory. We provide database credentials or JNDI resource information in the
hibernate configuration xml file. Some other important parts of hibernate configuration file
is Dialect information, so that hibernate knows the database type and mapping file or class
details.
1. javax.persistence.Entity: Used with model classes to specify that they are entity beans.
2. javax.persistence.Table: Used with entity beans to define the corresponding table name
in database.
3. 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.
4. javax.persistence.Id: Used to define the primary key in the entity bean.
5. javax.persistence.EmbeddedId: Used to define composite primary key in the entity
bean.
6. javax.persistence.Column: Used to define the column name in database table.
7. javax.persistence.GeneratedValue: Used to define the strategy to be used for
generation of primary key. Used in conjunction
with javax.persistence.GenerationTypeenum.
8. javax.persistence.OneToOne: Used to define the one-to-one mapping between two
entity beans. We have other similar annotations
as OneToMany, ManyToOne and ManyToMany
9. org.hibernate.annotations.Cascade: Used to define the cascading between two entity
beans, used with mappings. It works in conjunction
with org.hibernate.annotations.CascadeType
10. javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key.
Used
with org.hibernate.annotations.GenericGeneratorand org.hibe
rnate.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;
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;
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 provide methods to get the Class metadata and Statistics instance to
get the stats of query executions, second level cache details etc.
Session provide 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 Session object.
There is another method openStatelessSession() that returns stateless session, for more
details with examples please read Hibernate openSession vs getCurrentSession.
1. get() loads the data as soon as it’s called whereas load() returns a proxy object and loads
data only when it’s actually required, so load() is better because it support lazy loading.
2. Since load() throws exception when data is not found, we should use it only when we
know data exists.
3. We should use get() when we want to make sure data exists in the database.
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.
1. Add hibernate-ehcache dependency in your maven project, if it’s not maven then add
corresponding jars.
2.
3. <dependency>
4. <groupId>org.hibernate</groupId>
5. <artifactId>hibernate-ehcache</artifactId>
6. <version>4.3.5.Final</version>
7. </dependency>
8. Add below properties in hibernate configuration file.
9.
10. <property
name="hibernate.cache.region.factory_class">org.hibernat
e.cache.ehcache.EhCacheRegionFactory</property>
11.
12. <!-- For singleton factory -->
13. <!-- <property
name="hibernate.cache.region.factory_class">org.hibernat
e.cache.ehcache.SingletonEhCacheRegionFactory</property>
14. -->
15.
16. <!-- enable second level cache and query cache -->
17. <property
name="hibernate.cache.use_second_level_cache">true</prop
erty>
18. <property
name="hibernate.cache.use_query_cache">true</property>
19. <property
name="net.sf.ehcache.configurationResourceName">/myehcac
he.xml</property>
20. Create EHCache configuration file, a sample file myehcache.xml would look like below.
21.
22. <?xml version="1.0" encoding="UTF-8"?>
23. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
24. xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
25. monitoring="autodetect" dynamicConfig="true">
26.
27. <diskStore path="java.io.tmpdir/ehcache" />
28.
29. <defaultCache maxEntriesLocalHeap="10000"
eternal="false"
30. timeToIdleSeconds="120" timeToLiveSeconds="120"
diskSpoolBufferSizeMB="30"
31. maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
32. memoryStoreEvictionPolicy="LRU"
statistics="true">
33. <persistence strategy="localTempSwap" />
34. </defaultCache>
35.
36. <cache name="employee" maxEntriesLocalHeap="10000"
eternal="false"
37. timeToIdleSeconds="5" timeToLiveSeconds="10">
38. <persistence strategy="localTempSwap" />
39. </cache>
40.
41. <cache
name="org.hibernate.cache.internal.StandardQueryCache"
42. maxEntriesLocalHeap="5" eternal="false"
timeToLiveSeconds="120">
43. <persistence strategy="localTempSwap" />
44. </cache>
45.
46. <cache
name="org.hibernate.cache.spi.UpdateTimestampsCache"
47. maxEntriesLocalHeap="5000" eternal="true">
48. <persistence strategy="localTempSwap" />
49. </cache>
50. </ehcache>
51. Annotate entity beans with @Cache annotation and caching strategy to use. For
example,
52.
53. import org.hibernate.annotations.Cache;
54. import
org.hibernate.annotations.CacheConcurrencyStrategy;
55.
56. @Entity
57. @Table(name = "ADDRESS")
58. @Cache(usage=CacheConcurrencyStrategy.READ_ONLY,
region="employee")
59. public class Address {
60.
61. }
That’s it, we are done. Hibernate will use the EHCache for second level caching,
read Hibernate EHCache Example for a complete example with explanation.
What are different states of an entity bean?
An entity bean instance can exist is one of the three states.
1. Transient: When an object is never persisted or associated with any session, it’s in
transient state. Transient instances may be made persistent by calling save(), persist() or
saveOrUpdate(). Persistent instances may be made transient by calling delete().
2. Persistent: When an object is associated with a unique session, it’s in persistent state.
Any instance returned by a get() or load() method is persistent.
3. Detached: When an object is previously persistent but not associated with any session,
it’s in detached state. Detached instances may be made persistent by calling update(),
saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may
also be made persistent as a new persistent instance by calling merge().
2. 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. For example program,
read Hibernate merge.
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. For example usage of these methods, read Hibernate save
vs persist.
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<Employee> 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.
1. Bag
2. Set
3. List
4. Array
5. Map
7. How to implement Joins in Hibernate?
There are various ways to implement joins in hibernate.
Hibernate query language is case-insensitive except for java class and variable names. So
SeLeCT is the same as sELEct is the same as SELECT, but
com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE.
The HQL queries are cached but we should avoid it as much as possible, otherwise we will
have to take care of associations. However it’s a better choice than native sql query
because of Object-Oriented approach. Read more at HQL Example.
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. First of all we need to configure
below property in hibernate configuration file.
<property
name="hibernate.cache.use_query_cache">true</property>
And in code, we need to use setCacheable(true) method of Query, quick example looks
like below.
For normal scenarios, it is however not the recommended approach because we loose
benefits related to hibernate association and hibernate first level caching. Read more
at Hibernate Native SQL Query Example.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of
JPA annotations @NamedQuery and @NamedNativeQuery.
However one of the major disadvantage of Named query is that it’s hard to debug, because
we need to find out the location where it’s defined.
1. Criteria API provides Projection that we can use for aggregate functions such as sum(),
min(), max() etc.
2. Criteria API can be used with ProjectionList to fetch selected columns only.
3. Criteria API can be used for join queries by joining multiple tables, useful methods are
createAlias(), setFetchMode() and setProjection()
4. Criteria API can be used for fetching results with conditions, useful methods are add()
where we can add Restrictions.
5. Criteria API provides addOrder() method that we can use for ordering the results.
<property name="hibernate.show_sql">true</property>
However we should use it only in Development or Testing environment and turn it off in
production environment.
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.
4. 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.
1. Add log4j dependencies for maven project, if not maven then add corresponding jar
files.
2. 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.
3. For standalone projects, use static block to configure log4j
using DOMConfigurator or PropertyConfigurator. For web applications,
you can use ServletContextListener to configure it.
<property
name="hibernate.connection.datasource">java:comp/env/jdbc/My
LocalDB</property>
For a complete example, go through Hibernate JNDI DataSource Example.
1. Domain Model Pattern – An object model of the domain that incorporates both
behavior and data.
2. Data Mapper – A layer of Mappers that moves data between objects and a database
while keeping them independent of each other and the mapper itself.
3. Proxy Pattern for lazy loading
4. Factory pattern in SessionFactory
What are best practices to follow with Hibernate
framework?
Some of the best practices to follow in Hibernate are:
1. Always check the primary key field access, if it’s generated at the database layer then
you should not have a setter for this.
2. 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).
3. 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.
4. Use native sql query only when it can’t be done using HQL, such as using database
specific feature.
5. If you have to sort the collection, use ordered list rather than sorting it using Collection
API.
6. 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.
7. For web applications, always try to use JNDI DataSource rather than configuring to
create connection in hibernate.
8. Avoid Many-to-Many relationships, it can be easily implemented using bidirectional
One-to-Many and Many-to-One relationships.
9. For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit
of lazy loading.
10. 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.
11. Prefer DAO pattern for exposing the different methods that can be used with entity
bean
12. 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. Read more at Hibernate Validation Example.
JAVATPOINT
1) What is hibernate?
more details...
2) What is ORM?
more
details...
o Configuration
o SessionFactory
o Session
o Query
o Criteria
o Transaction
The objects of criteria are used for the creation and execution of the object-oriented
criteria queries.
o DB2
o MySQL
o Oracle
o Sybase SQL Server
o Informix Dynamic Server
o HSQL
o PostgreSQL
o FrontBase
o Configuration
o Session
o SessionFactory
o Criteria
o Query
o Transaction
Database Connection
The SQL query is created with the help of the following syntax:
Session.createSQLQuery
The HQL query is created with the help of the following syntax:
Session.createQuery
13) How can we add criteria to a SQL query?
Classes whose objects are stored in a database table are called as persistent classes.
more details...
It provides methods to store, update, delete or fetch data from the database such as
persist(), update(), delete(), load(), get() etc.
No, Session is not a thread-safe object, many threads can access it simultaneously. In
other words, you can share it between threads.
The differences between get() and load() methods are given below.
The differences between update() and merge() methods are given below.
1. ...
2. SessionFactory factory = cfg.buildSessionFactory();
3. Session session1 = factory.openSession();
4.
5. Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));/
/passing id of employee
6. session1.close();
7.
8. e1.setSalary(70000);
9.
10. Session session2 = factory.openSession();
11. Employee e2 = (Employee) session1.get(Employee.class, Integer.valueOf(101));/
/passing same id
12.
13. Transaction tx=session2.beginTransaction();
14. session2.merge(e1);
15.
16. tx.commit();
17. session2.close();
After closing session1, e1 is in detached state. It will not be in the session1 cache. So
if you call update() method, it will throw an error.
Then, we opened another session and loaded the same Employee instance. If we call
merge in session2, changes of e1 will be merged in e2.
more details...
1. ...
2. SessionFactory factory = cfg.buildSessionFactory();
3. Session session1 = factory.openSession();
4. Transaction tx=session2.beginTransaction();
5.
6. Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));
7.
8. e1.setSalary(70000);
9.
10. tx.commit();
11. session1.close();
Here, after getting employee instance e1 and we are changing the state of e1.
After changing the state, we are committing the transaction. In such a case, the state
will be updated automatically. This is known as dirty checking in hibernate.
1. One to One
2. One to Many
3. Many to One
4. Many to Many
No, collection mapping can only be performed with One-to-Many and Many-to-Many.
Lazy loading in hibernate improves the performance. It loads the child objects on
demand.
Since Hibernate 3, lazy loading is enabled by default, and you don't need to do
lazy="true". It means not to load the child objects when the parent is loaded.