Hibernate Questions
Hibernate Questions
Hibernate Questions
The aim of hibernate framework is to free the developer from the common data
persistence-related complex configurations and tasks. It does so by mapping the
POJO objects with the database tables efficiently and most importantly in an abstract
manner.
The developer need not know the underlying complications involved. Along with
abstraction, the queries can be executed in a very efficient manner. All these helps
developers to save a lot of time involved in development.
Top we will walk you through the top questions to get you ready for a Hibernate
interview. This article would cover basic, intermediate, and advanced questions.
Hibernate ORM stands for Object Relational Mapping. This is a mapping tool
pattern mainly used for converting data stored in a relational database to an object
used in object-oriented programming constructs. This tool also helps greatly in
simplifying data retrieval, creation, and manipulation.
Object Relational Mapping
Clean Readable Code: Using hibernate, helps in eliminating a lot of JDBC API-based
boiler-plate codes, thereby making the code look cleaner and readable.
HQL (Hibernate Query Language): Hibernate provides HQL which is closer to Java
and is object-oriented in nature. This helps in reducing the burden on developers for
writing database independent queries. In JDBC, this is not the case. A developer has
to know the database-specific codes.
Transaction Management: JDBC doesn't support implicit transaction management.
It is upon the developer to write transaction management code using commit and
rollback methods. Whereas, Hibernate implicity provides this feature.
Exception Handling: Hibernate wraps the JDBC exceptions and throws unchecked
exceptions like JDBCException or HibernateException. This along with the built-in
transaction management system helps developers to avoid writing multiple try-catch
blocks to handle exceptions. In the case of JDBC, it throws a checked exception called
SQLException thereby mandating the developer to write try-catch blocks to handle
this exception at compile time.
Special Features: Hibernate supports OOPs features like inheritance, associations
and also supports collections. These are not available in JDBC.
Configuration
SessionFactory
Session
Criteria
Query
Transaction
A session is an object that maintains the connection between Java object application
and database. Session also has methods for storing, retrieving, modifying or deleting
data from database using methods like persist(), load(), get(), update(), delete(), etc.
Additionally, It has factory methods to return Query, Criteria, and Transaction objects.
5. What is a SessionFactory?
This also provides the facility to get information like statistics and metadata related
to a class, query executions, etc. It also holds second-level cache data if enabled.
No, Session is not a thread-safe object which means that any number of threads can
access data from it simultaneously.
Lazy loading is mainly used for improving the application performance by helping to
load the child objects on demand.
It is to be noted that, since Hibernate 3 version, this feature has been enabled by
default. This signifies that child objects are not loaded until the parent gets loaded.
8. What is the difference between first level cache and second level
cache?
Hibernate has 2 cache types. First level and second level cache for which the
difference is given below:
First Level Cache Second Level Cache
This is local to the Session object and This cache is maintained at the
cannot be shared between multiple SessionFactory level and shared among all
sessions. sessions in Hibernate.
This cache is enabled by default and This is disabled by default, but we can
there is no way to disable it. enable it through configuration.
The first level cache is available only The second-level cache is available through
until the session is open, once the the application’s life cycle, it is only
session is closed, the first level cache is destroyed and recreated when an
destroyed. application is restarted.
If an entity or object is loaded by calling the get() method then Hibernate first
checked the first level cache, if it doesn’t find the object then it goes to the second
level cache if configured. If the object is not found then it finally goes to the
database and returns the object, if there is no corresponding row in the table then it
returns null.
Immutable class in hibernate creation could be in the following way. If we are using
the XML form of configuration, then a class can be made immutable by
markingmutable=false. The default value is true there which indicating that the class
was not created by default.
In the case of using annotations, immutable classes in hibernate can also be created
by using @Immutable annotation.
11. Can you explain the concept behind Hibernate Inheritance
Mapping?
Hibernate’s Inheritance Mapping strategies deal with solving how to hibernate being
an ORM tries to map this problem between the inheritance of Java and flat structure
of Databases.
The general employee details are defined in the parent InterviewBitEmployee class.
Hibernate does not provide immunity to SQL Injection. However, following good
practices avoids SQL injection attacks. It is always advisable to follow any of the
below options:
Hibernate mapping file is an XML file that is used for defining the entity bean fields
and corresponding database column mappings.
These files are useful when the project uses third-party classes where JPA
annotations provided by hibernating cannot be used.
<hibernate-mapping>
<!-- What class is mapped to what database table-->
<class name = "InterviewBitEmployee" table = "InterviewBitEmployee">
<meta attribute = "class-description">
This class contains the details of employees of InterviewBit.
</meta>
</class>
</hibernate-mapping>
import org.hibernate.annotations.Cascade;
@Entity
@Table(name = "InterviewBitEmployee")
@Access(value=AccessType.FIELD)
public class InterviewBitEmployee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "employee_id")
private long id;
@Column(name = "full_name")
private String fullName;
@Column(name = "email")
private String email;
@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
Java Application
Hibernate framework - Configuration and Mapping Files
Internal API -
o JDBC (Java Database Connectivity)
o JTA (Java Transaction API)
o JNDI (Java Naming Directory Interface).
Database - MySQL, PostGreSQL, Oracle, etc
Hibernate Architecture
SessionFactory: This provides a factory method to get session objects and clients of
ConnectionProvider. It holds a second-level cache (optional) of data.
Session: This is a short-lived object that acts as an interface between the java
application objects and database data.
o The session can be used to generate transaction, query, and criteria objects.
o It also has a mandatory first-level cache of data.
Transaction: This object specifies the atomic unit of work and has methods useful for
transaction management. This is optional.
ConnectionProvider: This is a factory of JDBC connection objects and it provides an
abstraction to the application from the DriverManager. This is optional.
TransactionFactory: This is a factory of Transaction objects. It is optional.
Hibernate Objects
Both the methods are provided by the Session Factory. The main differences are
given below:
getCurrentSession() openSession()
This method returns the session bound to the This method always opens a
context. new session.
This session object scope belongs to the hibernate
context and to make this work hibernate A new session object has to
configuration file has to be modified by be created for each request in
adding <property name = a multi-threaded
"hibernate.current_session_context_class"> thread environment. Hence, you
getCurrentSession() openSession()
</property>. If not added, then using the method need not configure any
would throw an HibernateException. property to call this method.
It's the developer’s
responsibility to close this
This session object gets closed once the session object once all the database
factory is closed. operations are done.
In single threaded
environment, it is slower than
In a single-threaded environment, this method is getCurrentSession()single-
faster than openSession(). threadeda
Apart from these two methods, there is another method openStatelessSession() and
this method returns a stateless session object.
Both the methods save records to the table in the database in case there are no
records with the primary key in the table. However, the main differences between
these two are listed below:
save() saveOrUpdate()
save() generates a new
identifier and INSERT record Session.saveOrUpdate() can either INSERT or
into a database UPDATE based upon existence of a record.
The insertion fails if the
primary key already exists in In case the primary key already exists, then the
the table. record is updated.
The return type is Serializable
which is the newly generated
identifier id value as a The return type of the saveOrUpdate() method is
Serializable object. void.
This method can bring both transient (new) and
This method is used to bring detached (existing) objects into a persistent state. It
only a transient object to a is often used to re-attach a detached object into a
persistent state. Session
get() load()
This method gets the data from
the database as soon as it is This method returns a proxy object and loads the
called. data only when it is required.
The database is hit only when it is really needed
The database is hit every time and this is called Lazy Loading which makes the
the method is called. method better.
The method returns null if the The method throws ObjectNotFoundException if
object is not found. the object is not found.
This method should be used if
we are unsure about the
existence of data in the This method is to be used when we know for sure
database. that the data is present in the database.
Criteria API in Hibernate helps developers to build dynamic criteria queries on the
persistence database. Criteria API is a more powerful and flexible alternative to HQL
(Hibernate Query Language) queries for creating dynamic queries.
It also makes it very easy to incorporate restrictions to selectively retrieve data from
the database. It can be achieved by using the add() method which accepts the
org.hibernate.criterion.Criterion object representing individual restriction.
Usage examples:
To retrive objects whose property has value equal to the restriction, we use
Restrictions.eq() method. For example, to fetch all records with name
‘Hibernate’:
To get objects whose property has the value “not equal to” the restriction, we
use Restrictions.ne() method. For example, to fetch all the records whose
employee’s name is not Hibernate:
Similarly, it also has other methods like isNull(), isNotNull(), gt(), ge(), lt(), le() etc for
adding more varieties of restrictions. It has to be noted that for Hibernate 5 onwards,
the functions returning an object of typeCriteria are deprecated. Hibernate 5 version
has provided interfaces like CriteriaBuilder and CriteriaQuery to serve the purpose:
javax.persistence.criteria.CriteriaBuilder
javax.persistence.criteria.CriteriaQuery
// Create CriteriaBuilder
CriteriaBuilder builder = session.getCriteriaBuilder();
// Create CriteriaQuery
CriteriaQuery<YourClass> criteria = builder.createQuery(YourClass.class);
This makes use of the Query interface provided by Hibernate. The Query object is
obtained by calling the createQuery() method of the hibernate Session interface.
21. Can you tell something about one to many associations and how
can we use them in Hibernate?
The one-to-many association is the most commonly used which indicates that one
object is linked/associated with multiple objects.
@Entity
@Table(name="Person")
public class Person {
//...
@OneToMany(mappedBy="owner")
private Set<Car> cars;
In the Person class, we have defined the car's property to have @OneToMany
association. The Car class would have owned property that is used by the mappedBy
variable in the Person class. The Car class is as shown below:
@Entity
@Table(name="Car")
public class Car {
// Other Properties
@ManyToOne
@JoinColumn(name="person_id", nullable=false)
private Person owner;
public Car() {}
Many-to-many association indicates that there are multiple relations between the
instances of two entities. We could take the example of multiple students taking part
in multiple courses and vice versa.
Since both the student and course entities refer to each other by means of foreign
keys, we represent this relationship technically by creating a separate table to hold
these foreign keys.
Here, Student-Course Table is called the Join Table where the student_id and
course_id would form the composite primary key.
23. What does session.lock() method in hibernate do?
Second level cache resides in the SessionFactory object and due to this, the data is
accessible by the entire application.
This is not available by default. It has to be enabled explicitly.
EH (Easy Hibernate) Cache, Swarm Cache, OS Cache, JBoss Cache are some example
cache providers.
Second Level Caching
Merge() method can be used for updating existing values. The specialty of this
method is, once the existing values are updated, the method creates a copy from the
entity object and returns it. This result object goes into the persistent context and is
then tracked for any changes. The object that was initially used is not tracked.
setFetchSize() works for optimizing how Hibernate sends the result to the caller for
example: are the results buffered, are they sent in different size chunks, etc. This
method is not implemented by all the database drivers.
Yes, it does. Hibernate provides the createSQLQuery() method to let a developer call
the native SQL statement directly and returns a Query object.
Consider the example where you want to get employee data with the full name
“Hibernate”. We don’t want to use HQL-based features, instead, we want to write our
own SQL queries. In this case, the code would be:
Hibernate framework internally uses Reflection API for creating entity bean instances
when get() or load() methods are called. The method Class.newInstance() is used
which requires a no-args constructor to be present. When we don't have this
constructor in the entity beans, then hibernate fails to instantiate the bean and hence
it throws HibernateException.
No, we should not define the entity class final because hibernate uses proxy classes
and objects for lazy loading of data and hits the database only when it is absolutely
needed. This is achieved by extending the entity bean. If the entity class (or bean) is
made final, then it cant be extended and hence lazy loading can not be supported.
Transient:
Persistent:
This state is entered whenever the object is linked or associated with the session.
An object is said to be in a persistence state whenever we save or persist an object in
the database. Each object corresponds to the row in the database table. Any
modifications to the data in this state cause changes in the record in the database.
session.save(record);
session.persist(record);
session.update(record);
session.saveOrUpdate(record);
session.lock(record);
session.merge(record);
Detached:
The object enters this state whenever the session is closed or the cache is cleared.
Due to the object being no longer part of the session, any changes in the object will
not reflect in the corresponding row of the database. However, it would still have its
representation in the database.
In case the developer wants to persist changes of this object, it has to be reattached
to the hibernate session.
In order to achieve the reattachment, we can use the methods load(), merge(),
refresh(), update(), or save() methods on a new session by using the reference of the
detached object.
The object enters this state whenever any of the following methods are called:
session.close();
session.clear();
session.detach(record);
session.evict(record);
Persistent Entity
Hibernate framework provides an optional feature called cache region for the
queries’ resultset. Additional configurations have to be done in code in order to
enable this. The query cache is useful for those queries which are most frequently
called with the same parameters. This increases the speed of the data retrieval and
greatly improves performance for commonly repetitive queries.
This does not cache the state of actual entities in the result set but it only stores the
identifier values and results of the value type. Hence, query cache should be always
used in association with second-level cache.
Configuration:
In the hibernate configuration XML file, set the use_query_cache property to true as
shown below:
<property name="hibernate.cache.use_query_cache">true</property>
In the code, we need to do the below changes for the query object:
Query query = session.createQuery("from InterviewBitEmployee");
query.setCacheable(true);
query.setCacheRegion("IB_EMP");
33. Can you tell something about the N+1 SELECT problem in
Hibernate?
N+1 SELECT problem is due to the result of using lazy loading and on-demand
fetching strategy. Let's take an example. If you have an N items list and each item
from the list has a dependency on a collection of another object, say bid. In order to
find the highest bid for each item while using the lazy loading strategy, hibernate has
to first fire 1 query to load all items and then subsequently fire N queries to load big
of each item. Hence, hibernate actually ends up executing N+1 queries.
Some of the strategies followed for solving the N+1 SELECT problem are:
Pre-fetch the records in batches which helps us to reduce the problem of N+1 to
(N/K) + 1 where K refers to the size of the batch.
Subselect the fetching strategy
As last resort, try to avoid or disable lazy loading altogether.
Concurrency strategies are the mediators responsible for storing and retrieving items
from the cache. While enabling second-level cache, it is the responsibility of the
developer to provide what strategy is to be implemented to decide for each
persistent class and collection.
Transactional: This is used in cases of updating data that most likely causes stale
data and this prevention is most critical to the application.
Read-Only: This is used when we don't want the data to be modified and can be
used for reference data only.
Read-Write: Here, data is mostly read and is used when the prevention of stale data
is of critical importance.
Non-strict-Read-Write: Using this strategy will ensure that there wouldn't be any
consistency between the database and cache. This strategy can be used when the
data can be modified and stale data is not of critical concern.
36. What is Single Table Strategy?
For the example defined in the Hibernate Inheritance Mapping question above, if we
follow this single table strategy, then all the permanent and contract employees’
details are stored in only one table called InterviewBitEmployee in the database and
the employees would be differentiated by making use of discriminator column
named employee_type.
InterviewBitEmployee class:
@Entity
@Table(name = "InterviewBitEmployee")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitEmployee {
@Id
@Column(name = "employee_id")
private String employeeId;
private String fullName;
private String email;
}
InterviewBitContractEmployee class:
@Entity
@DiscriminatorValue("contract")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitContractEmployee extends InterviewBitEmployee {
private LocalDate contractStartDate;
private LocalDate contractEndDate;
private String agencyName;
}
InterviewBitPermanentEmployee class:
@Entity
@DiscriminatorValue("permanent")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitPermanentEmployee extends InterviewBitEmployee {
private LocalDate workStartDate;
private int numberOfLeaves;
}
37. Can you tell something about Table Per Class Strategy.
Table Per Class Strategy is another type of inheritance mapping strategy where each
class in the hierarchy has a corresponding mapping database table. For example, the
InterviewBitContractEmployee class details are stored in the
interviewbit_contract_employee table and InterviewBitPermanentEmployee class
details are stored in interviewbit_permanent_employee tables respectively. As the
data is stored in different tables, there will be no need for a discriminator column as
done in a single table strategy.
InterviewBitEmployee class:
@Entity(name = "interviewbit_employee")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitEmployee {
@Id
@Column(name = "employee_id")
private String employeeId;
private String fullName;
private String email;
}
InterviewBitContractEmployee class:
@Entity(name = "interviewbit_contract_employee")
@Table(name = "interviewbit_contract_employee")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitContractEmployee extends InterviewBitEmployee {
private LocalDate contractStartDate;
private LocalDate contractEndDate;
private String agencyName;
}
InterviewBitPermanentEmployee class:
@Entity(name = "interviewbit_permanent_employee")
@Table(name = "interviewbit_permanent_employee")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitPermanentEmployee extends InterviewBitEmployee {
private LocalDate workStartDate;
private int numberOfLeaves;
}
Disadvantages:
This type of strategy offers less performance due to the need for additional joins to
get the data.
This strategy is not supported by all JPA providers.
Ordering is tricky in some cases since it is done based on a class and later by the
ordering criteria.
A named SQL query is an expression represented in the form of a table. Here, SQL
expressions to select/retrieve rows and columns from one or more tables in one or
more databases can be specified. This is like using aliases to the queries.
@NamedQueries(
{
@NamedQuery(
name = "findIBEmployeeByFullName",
query = "from InterviewBitEmployee e where e.fullName = :fullName"
)
}
)
:fullName refers to the parameter that is programmer defined and can be set using
the query.setParameter method while using the named query.
Usage:
The getNamedQuery method takes the name of the named query and returns the
query instance.
Conclusion
Hibernate is the most powerful open source ORM tool that is used for mapping java
objects with the database structures at run time. It has become more popular among
software developers due to its nature of abstraction allowing developers to continue
application development by being database independent and focus just on the
application business logic.
Additional Resources
Practice Coding
Java Tutorials
Hibernate MCQs
1.
Which among the below do not belong to the core interface of Hibernate?
SessionManagement
Configuration
Session
Criteria
2.
getDatabase()
get()
loadDatabase()
load()
3.
end()
merge()
update()
kill()
4.
True
False
There is no such class named PersisterClassProvider
Nothing is set by default
5.
What are the ways to map tables in the case of Table per Concrete class where there
would be three tables in the database that have no relation to each other?
By self-creating the table for each class
By union-subclass element
Both a & b
None of the above
7.
What holds the second level cache as per the Hibernate architecture?
Session
SessionFactory
Connection
Transaction
8.
By using annotations, we ensure that all metadata is clubbed into java file
thereby helping user to understand the table and POJO structure simultaneously
They are the powerful means to provide the metadata of the Object and
Relational Table mapping.
Both of the above
None of the above
9.
Which method among the following options hits the database always?
getDatabase()
load()
get()
loadDatabase()
10.
Hibernate is one of the most popular Java frameworks that simplify the
development of Java application to interact with the database. It is an Object-relational
mapping (ORM) tool. Hibernate also provides a reference implementation of Java API.
It is referred as a framework which comes with an abstraction layer and also handles
the implementations internally. The implementations include tasks like writing a query
for CRUDoperations or establishing a connection with the databases, etc.
Hibernate develops persistence logic, which stores and processes the data for longer
use. It is a lightweight tool and most importantly open-sourced which gives it an edge
over other frameworks.
1. Hibernate eliminates a lot of boiler-plate code that comes with JDBC API, the code
looks cleaner and readable.
2. This Java framework supports inheritance, associations, and collections. These
features are actually not present in JDBC.
3. HQL (Hibernate Query Language) is more object-oriented and close to Java. But for
JDBC, you need to write native SQL queries.
4. Hibernate implicitly provides transaction management whereas, in JDBC API, you
need to write code for transaction management using commit and rollback.
5. JDBC throws SQLException that is a checked exception, so you have to write a lot of
try-catch block code. Hibernate wraps JDBC exceptions and
throw JDBCException or HibernateExceptionwhich are the unchecked exceptions, so
you don’t have to write code to handle it has built-in transaction management which
helps in removing the usage of try-catch blocks.
XDoclet Spring
Maven
Eclipse Plug-ins
J2EE
Association mappings are one of the key features of Hibernate. It supports the same
associations as the relational database model. They are:
One-to-One associations
Many-to-One associations
Many-to-Many associations
SessionFactory (org.hibernate.SessionFactory)
Session (org.hibernate.Session)
Transaction (org.hibernate.Transaction)
In this type of mapping, you only need to model the system for the entity for which
you want to navigate the relationship in your query or domain model. You need an
entity attribute that represents the association, so annotate it with
an @OneToOne annotation.
In this type of association, one object can be associated with multiple/different objects.
Talking about the mapping, the One-to-Many mapping is implemented using a Set
Java collection that does not have any redundant element. This One-to-Many element
of the set indicates the relation of one object to multiple objects.
Spring is also one of the most commonly used Java frameworks in the market
today. Spring is a JavaEE Framework and Hibernate is the most popular ORM
framework. This is why Spring Hibernate combination is used in a lot of enterprise
applications.
Following are the steps you should follow to integrate Spring and Hibernate.
1. Add Hibernate-entity manager, Hibernate-core and Spring-ORM dependencies.
2. Create Model classes and corresponding DAO implementations for database
operations. The DAO classes will use SessionFactory that will be injected by the
Spring Bean configuration.
3. Note that you don’t need to use Hibernate Transaction Management, as you can leave
it to the Spring declarative transaction management using @Transactional annotation.
1. javax.persistence.Entity: This is used with model classes to specify they are entity
beans.
2. javax.persistence.Table: It is used with entity beans to define the corresponding table
name in the database.
3. javax.persistence.Access: Used to define the access type, field or property. The
default value is field and if you want Hibernate to use the getter/setter methods then
you need to set it to a property.
4. javax.persistence.Id: Defines the primary key in the entity bean.
5. javax.persistence.EmbeddedId: It defines a composite primary key in the entity
bean.
6. javax.persistence.Column: Helps in defining the column name in the database table.
7. javax.persistence.GeneratedValue: It defines the strategy to be used for the
generation of the primary key. It is also used in conjunction
with javax.persistence.GenerationType enum.
Hibernate Session is the interface between Java application layer and Hibernate. It is
used to get a physical connection with the database. The Session object created is
lightweight and designed to be instantiated each time an interaction is needed with the
database. This Session provides methods to create, read, update and delete
operations for a constant object. To get the Session, you can execute HQL queries,
SQL native queries using the Session object.
SessionFactory is the factory class that is used to get the Session objects. The
SessionFactory is a heavyweight object so usually, it is created during application
startup and kept for later use. This SessionFactory is a thread-safe object which is
used by all the threads of an application. If you are using multiple databases then you
would have to create multiple SessionFactory objects.
This getCurrentSession() method returns the session bound to the context and for this
to work, you need to configure it in Hibernate configuration file. Since this session
object belongs to the context of Hibernate, it is okay if you don’t close it. Once
the SessionFactory is closed, this session object gets closed.
Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access
Explore Curriculum
openSession() method helps in opening a new session. You should close this session
object once you are done with all the database operations. And also, you should open
a new session for each request in a multi-threaded environment.
1. First, identify the POJOs (Plain Old Java Objects) that have a database representation.
2. Identify which properties of POJOs need to be continued.
3. Annotate each of the POJOs in order to map the Java objects to columns in a database
table.
4. Create a database schema using the schema export tool which uses an existing
database, or you can create your own database schema.
5. Add Hibernate Java libraries to the application’s classpath.
6. Create a Hibernate XML configuration file that points to the database and the mapped
classes.
7. In the Java application, you can create a Hibernate Configuration object that refers to
your XML configuration file.
8. Also, build a Hibernate SessionFactory object from the Configuration object.
9. Retrieve the Hibernate Session objects from the SessionFactory and write down the
data access logic for your application (create, retrieve, update, and delete).
Hibernate provides the facility to persist the Collections. A Collection basically can be
a List, Set, Map, Collection, Sorted Set, Sorted Map. java.util.List, java.util.Set,
java.util.Collection, etc, are some of the real interface types to declared the persistent
collection-value fields. Hibernate injects persistent Collections based on the type of
interface. The collection instances generally behave like the types of value behavior.
There are five collection types in hibernate used for one-to-many relationship
mappings.
Bag
Set
List
Array
Map
When you integrate Spring and Hibernate, Spring ORM provides two helper classes
– HibernateDaoSupport and HibernateTemplate. The main reason to use them was to
get two things, the Session from Hibernate and Spring Transaction Management.
However, from Hibernate 3.0.1, you can use the
SessionFactory getCurrentSession() method to get the current session. The major
advantage of using this Template class is the exception translation but that can be
achieved easily by using @Repository annotation with service classes.
The following are the benefits of using this Hibernate template class:
Domain Model Pattern: An object model of the domain that incorporates both
behavior as well as data.
Data Mapper: A layer of the map that moves data between objects and a database
while keeping it independent of each other and the map itself.
Proxy Pattern: It is used for lazy loading.
Factory Pattern: Used in SessionFactory.
Hibernate incorporates Dirty Checking feature that permits developers and users to
avoid time-consuming write actions. This Dirty Checking feature changes or updates
fields that need to be changed or updated, while keeping the remaining fields
untouched and unchanged.
Q29. How can you share your views on mapping description files?
The means that the syntax is hidden from the business logic using specific design
patterns. This is one of the valuable levels of ORM quality and this Light Object
Mapping approach can be successful in case of applications where there are very
fewer entities, or for applications having data models that are metadata-driven.
Q33. How do you integrate Hibernate with Struts2 or Servlet web applications?
You can integrate any Struts application with Hibernate. There are no extra efforts
required.
Transient: This is not associated with the Session and has no representation in the
database.
3 <generator/>
4 </id>
Q36. Explain about Hibernate Proxy and how it helps in Lazy loading?
Hibernate uses a proxy object in order to support Lazy loading.
When you try loading data from tables, Hibernate doesn’t load all the mapped
objects.
After you reference a child object through getter methods, if the linked entity is not
present in the session cache, then the proxy code will be entered to the database
and load the linked object.
It uses Java assist to effectively and dynamically generate sub-classed
implementations of your entity objects.
In order to view the SQL on a console, you need to add following in Hibernate
configuration file to enable viewing SQL on the console for debugging purposes:
1 <property name="show_sql">true</property>
Hibernate implements a separate cache region for queries resultset that integrates
with the Hibernate second-level cache. This is also an optional feature and requires a
few more steps in code.
5(2005)
4(47134)
5(10077)
PYTHON DJANGO TRAINING AND CERTIFICATION
Python Django Training and Certification
Reviews
5(5655)
5(8658)
5(6535)
5(3591)
5(4358)
Next
Note: This is only useful for queries that are run frequently with the same parameters.
Hibernate provides an option to execute Native SQL queries through the use of
the SQLQuery object. For normal scenarios, it is however not the recommended
approach because you might lose other benefits like Association and Hibernate first-
level caching.
Native SQL Query comes handy when you want to execute database-specific queries
that are not supported by Hibernate API such query hints or the Connect keyword in
Oracle Database.
Hibernate provides another important feature called Named Query using which you
can define at a central location and use them anywhere in the code.
You can create named queries for both HQL as well as for Native SQL. These Named
Queries can be defined in Hibernate mapping files with the help of JPA annotations
@NamedQuery and @NamedNativeQuery.
update(): If you are sure that the Hibernate Session does not contain an already
persistent instance with the same id .
merge(): Helps in merging your modifications at any time without considering the
state of the Session.
This is one of the most frequently asked Hibernate Interview Questions. The key
difference between the get() and load() method is:
load(): It will throw an exception if an object with an ID passed to them is not found.
get(): Will return null.
load(): It can return proxy without hitting the database unless required.
get(): It always goes to the database.
Q43. Difference between the first and second level cache in Hibernate?
The first-level cache is maintained at Session level while the second level cache is
maintained at a SessionFactory level and is shared by all sessions.
Even though save() and saveOrUpdate() method is used to store an object into
Database, the key difference between them is that save() can only Insert records
but saveOrUpdate() can either Insert or Update records.
sorted collection sort the data in JVM’s heap memory using Java’s collection
framework sorting methods. The ordered collection is sorted using order by clause in
the database itself.
Note: A sorted collection is more suited for small dataset but for a large dataset, it’s
better to use ordered collection to avoid
Transient state: New objects are created in the Java program but are not associated
with any Hibernate Session.
Q49. What are the best practices that Hibernate recommends for persistent
classes?
Q50. What are the best practices to follow with Hibernate framework?
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 the
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 a 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 the 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
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.
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 file comes handy when we are
using third party classes and we can’t use annotations.
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;
Hibernate Session object is not thread safe, every thread should get it’s
own session instance and close it after it’s work is finished.
<property
name="hibernate.current_session_context_class">thread</proper
ty>
14. What is difference between Hibernate Session get() and load() method?
Hibernate session comes with different methods to load data from
database. get and load are most used methods, at first look they seems
similar but there are some differences between them.
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.
For clarification regarding the differences, please read Hibernate get vs load.
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.
EHCache is the best choice for utilizing hibernate second level cache.
Following steps are required to enable EHCache in hibernate application.
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.
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.
20. What will happen if we don’t have no-args constructor in Entity bean?
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.
0. Bag
1. Set
2. List
3. Array
4. Map
Hibernate use proxy classes for lazy loading of data, only when it’s needed.
This is done by extending the entity bean, if the entity bean will be final
then lazy loading will not be possible, hence low performance.
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.
<property
name="hibernate.cache.use_query_cache">true</property>
Hibernate provide option to execute native SQL queries through the use
of SQLQueryobject.
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.
o Criteria API provides Projection that we can use for aggregate functions
such as sum(), min(), max() etc.
o Criteria API can be used with ProjectionList to fetch selected columns only.
o Criteria API can be used for join queries by joining multiple tables, useful
methods are createAlias(), setFetchMode() and setProjection()
o Criteria API can be used for fetching results with conditions, useful
methods are add() where we can add Restrictions.
o Criteria API provides addOrder() method that we can use for ordering the
results.
We can set below property for hibernate configuration to log SQL queries.
<property name="hibernate.show_sql">true</property>
Hibernate uses proxy object to support lazy loading. Basically when you
load data from tables, hibernate doesn’t load all the mapped objects. As
soon as you reference a child or lookup object via getter methods, if the
linked entity is not in the session cache, then the proxy code will go to the
database and load the linked object. It uses javassist to effectively and
dynamically generate sub-classed implementations of your entity objects.
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:
0. None: No Cascading, it’s not a type but when we don’t define any
cascading then no operations in parent affects the child.
1. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist.
Basically everything
2. SAVE_UPDATE: Cascades save and update, available only in hibernate.
3. DELETE: Corresponds to the Hibernate native DELETE action, only in
hibernate.
4. DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar
operations
5. LOCK: Corresponds to the Hibernate native LOCK action.
6. REPLICATE: Corresponds to the Hibernate native REPLICATE action.
Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions.
For log4j configuration, we need to follow below steps.
o Add log4j dependencies for maven project, if not maven then add
corresponding jar files.
o 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.
o For standalone projects, use static block to configure log4j
using DOMConfigurator or PropertyConfigurator. For web applications,
you can use ServletContextListener to configure it.
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/MyL
ocalDB</property>
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.
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.
o Always check the primary key field access, if it’s generated at the database
layer then you should not have a setter for this.
o 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).
o 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.
o Use native sql query only when it can’t be done using HQL, such as using
database specific feature.
o If you have to sort the collection, use ordered list rather than sorting it using
Collection API.
o 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.
o For web applications, always try to use JNDI DataSource rather than
configuring to create connection in hibernate.
o Avoid Many-to-Many relationships, it can be easily implemented using
bidirectional One-to-Many and Many-to-One relationships.
o For collections, try to use Lists, maps and sets. Avoid array because you
don’t get benefit of lazy loading.
o 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.
o Prefer DAO pattern for exposing the different methods that can be used
with entity bean
o Prefer lazy fetching for associations
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.
45. What is the benefit of Hibernate Tools Eclipse plugin?