0% found this document useful (0 votes)
21 views54 pages

Hibenate

The document discusses Hibernate, a popular Java-based ORM tool, highlighting its advantages over other ORM tools and JDBC, such as reduced boilerplate code and support for lazy initialization. It explains key concepts like the N+1 problem, Hibernate exceptions, generator classes, and the importance of the Dialect class. Additionally, it covers Hibernate's caching mechanisms, configuration files, and essential annotations for mapping entities to database tables.

Uploaded by

indhu jayan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views54 pages

Hibenate

The document discusses Hibernate, a popular Java-based ORM tool, highlighting its advantages over other ORM tools and JDBC, such as reduced boilerplate code and support for lazy initialization. It explains key concepts like the N+1 problem, Hibernate exceptions, generator classes, and the importance of the Dialect class. Additionally, it covers Hibernate's caching mechanisms, configuration files, and essential annotations for mapping entities to database tables.

Uploaded by

indhu jayan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 54

Hibernate

1).Why Hibernate popular than othe ORM tools?

Let’s assume that you’re writing code that’d track the price of mobile phones. Now, let’s say
you have a collection of objects representing different Mobile phone vendors (MobileVendor),
and each vendor has a collection of objects representing the PhoneModels they offer.

To put it simple, there’s exists a one-to-many relationship between


MobileVendor:PhoneModel.

MobileVendor Class

Class MobileVendor{

long vendor_id;

PhoneModel[] phoneModels;

...

Okay, so you want to print out all the details of phone models. A naive O/R implementation
would SELECT all mobile vendors and then do N additional SELECTs for getting the information
of PhoneModel for each vendor.
-- Get all Mobile Vendors

SELECT * FROM MobileVendor;

-- For each MobileVendor, get PhoneModel details

SELECT * FROM PhoneModel WHERE MobileVendor.vendorId=?

As you see, the N+1 problem can happen if the first query populates the primary object and
the second query populates all the child objects for each of the unique primary objects
returned.

Resolve N+1 SELECTs problem

(i) HQL fetch join

"from MobileVendor mobileVendor join fetch mobileVendor.phoneModel PhoneModels"

Corresponding SQL would be (assuming tables as follows: t_mobile_vendor for MobileVendor


and t_phone_model for PhoneModel)

SELECT * FROM t_mobile_vendor vendor LEFT OUTER JOIN t_phone_model model ON


model.vendor_id=vendor.vendor_id

(ii) Criteria query


Criteria criteria = session.createCriteria(MobileVendor.class);

criteria.setFetchMode("phoneModels", FetchMode.EAGER);

In both cases, our query returns a list of MobileVendor objects with the phoneModels
initialized. Only one query needs to be run to return all the PhoneModel and MobileVendor
information required.

2).Hibernate Exceptions?

IllegalArgumentException: Wrong argument or fail to recognized, or having the incorrect


format etc.

EntityNotFoundException: An Entity was expected but did not match the requirement

TransactionRequiredException: This operation has to be in a Transaction object

IllegalStateException: Wrong way of using the Entity Manager

LazyInitializationException

Hibernate throws a LazyInitializationException if you try to access a not initialized relationship


to another entity without an active session. You can see a simple example for this in the
following code snippet.

OptimisticLockException

Another very common exception is the OptimisticLockException. Hibernate throws it when


you use optimistic locking and detects a conflicting update of an entity. That most often
happens for one of two reasons:

2 users try to update the same entity at nearly the same point in time

1 user performs 2 updates of the same entity, and developers didn’t refresh the entity
representation in the client so that the version value wasn’t updated after the first update

Developers can see a test case with 2 concurrent updates in the following code snippet.

3).Generator classes in Hibernate


Hibernate Architecture

Hibernate Framework

Advantages of Hibernate Framework

The <generator> class is a sub-element of id. It is used to generate the unique identifier for the
objects of persistent class. There are many generator classes defined in the Hibernate
Framework.

All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The


application programmer may create one's own generator classes by implementing the
IdentifierGenerator interface. Hibernate framework provides many built-in generator classes:

assigned

increment

sequence

hilo

native

identity

seqhilo

uuid

guid

select

foreign

sequence-identity

https://www.javatpoint.com/generator-classes
4).Why we need Dialect class?

Dialect class is java class, which contains code to map between java language data type
database data type.

All Dialect classes extend the Dialect abstract class.

Dialect is used to convert HQL statements to data base specific statements.

5).Difference between list and iterator in hibernate

list() iterate()

1 With one database hit, all the records are loaded For each record, one database
hit is made

2 if no cache data is available, this is faster if no chache data is available,


this is very slower

3 Eager loading Lazy loading

6).How to enable Cache in hibernate?

Hibernate second level cache uses a common cache for all the session object of a session
factory. It is useful if you have multiple session objects from a session factory.

SessionFactory holds the second level cache data. It is global for all the session objects and not
enabled by default.

Different vendors have provided the implementation of Second Level Cache.

EH Cache

OS Cache

Swarm Cache

JBoss Cache

Each implementation provides different cache usage functionality. There are four ways to use
second level cache.
read-only: caching will work for read only operation.

nonstrict-read-write: caching will work for read and write but one at a time.

read-write: caching will work for read and write, can be used simultaneously.

transactional: caching will work for transaction.

The cache-usage property can be applied to class or collection level in hbm.xml file. The
example to define cache usage is given below:

<cache usage="read-only" />

Let's see the second level cache implementation and cache usage.

Implementation read-only nonstrict-read-write read-write transactional

EH Cache Yes Yes Yes No

OS Cache Yes Yes Yes No

Swarm Cache Yes Yes No No

JBoss Cache No No No Yes

Hibernate Second Level Cache Example

To understand the second level cache through example, we need to follow the following steps:

Create the persistent class using Maven

Add project information and configuration in pom.xml file

Create the Configuration file

Create the class that retrieves the persistent object.


Here, we are assuming, there is emp1012 table in the oracle database containing some
records.

1) Create the persistent class using Maven.

File: Employee.java

package com.javatpoint;

import javax.persistence.*;

import org.hibernate.annotations.Cache;

import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity

@Table(name="emp1012")

@Cacheable

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

public class Employee {

@Id

private int id;

private String name;

private float salary;

public Employee() {}

public Employee(String name, float salary) {

super();

this.name = name;

this.salary = salary;

public int getId() {


return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public float getSalary() {

return salary;

public void setSalary(float salary) {

this.salary = salary;

2) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag.

<dependency>

<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>

<version>5.2.16.Final</version>

</dependency>

<dependency>

<groupId>com.oracle</groupId>

<artifactId>ojdbc14</artifactId>

<version>10.2.0.4.0</version>

</dependency>

<dependency>

<groupId>net.sf.ehcache</groupId>

<artifactId>ehcache</artifactId>

<version>2.10.3</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-ehcache</artifactId>

<version>5.2.16.Final</version>

</dependency>

3) Create the Configuration file

File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 5.2.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-5.2.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="show_sql">true</property>

<property name="hbm2ddl.auto">update</property>

<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

<property name="connection.username">system</property>

<property name="connection.password">jtp</property>

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<property name="cache.use_second_level_cache">true</property>

<property
name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</
property>

<mapping class="com.javatpoint.Employee"/>

</session-factory>

</hibernate-configuration>

To implement second level cache, we need to define cache.provider_class property in the


configuration file.
4) Create the class that retrieves the persistent object.

File: FetchTest.java

package com.javatpoint;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.boot.Metadata;

import org.hibernate.boot.MetadataSources;

import org.hibernate.boot.registry.StandardServiceRegistry;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class FetchTest {

public static void main(String[] args) {

StandardServiceRegistry ssr=new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory=meta.getSessionFactoryBuilder().build();

Session session1=factory.openSession();

Employee emp1=(Employee)session1.load(Employee.class,121);

System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());

session1.close();

Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);

System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());

session2.close();

Output:

hibernate second level cache output

As we can see here, hibernate does not fire query twice. If you don't use second level cache,
hibernate will fire query twice because both query uses different session objects.

 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 java based ORM tool
that provides framework for mapping application domain objects to the relational
database tables and vice versa.

 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.

  What is Java Persistence API (JPA)?

 Java Persistence API (JPA) provides specification for managing the relational data in
applications. 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 is defined with annotations in javax.persistence package. Using JPA
annotation 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:

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.

 What are the advantages of Hibernate over JDBC?

 Some of the important advantages of Hibernate framework over JDBC are:

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.

 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 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.

  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 file comes handy when we are using third party classes and we can’t use
annotations.

  Name some important annotations used for


Hibernate mapping?
 Hibernate supports JPA annotations and it has some other annotations in
org.hibernate.annotations package. Some of the important JPA and hibernate
annotations used are:

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.GenerationType enum.
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.GenericGenerator and
org.hibernate.annotations.Parameter

Here are two classes showing usage of these 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;

//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 to read the hibernate configuration parameters and connect to the database
and provide 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 provide 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 java application layer and hibernate. This is
the core interface used to perform database operations. Lifecycle of a session is bound by
the beginning and end of a transaction.

 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.

  Hibernate Session is thread safe?

 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.

  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 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 multi-threaded environment.

 There is another method openStatelessSession() that returns stateless session, for more
details with examples please read Hibernate openSession vs getCurrentSession.
  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.

 What is hibernate caching? Explain Hibernate 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.

 For better explanation, please read Hibernate First Level Cache.

  How to configure Hibernate 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.cac
he.ehcache.EhCacheRegionFactory</property>
<!-- For singleton factory --><!-- <property
name="hibernate.cache.region.factory_class">org.hibernate.ca
che.ehcache.SingletonEhCacheRegionFactory</property>
-->
<!-- enable second level cache and query cache --
><property
name="hibernate.cache.use_second_level_cache">true</proper
ty><property
name="hibernate.cache.use_query_cache">true</property><pr
operty
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="http://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 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().

 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.

  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. For example usage of these methods,
read Hibernate save vs persist.

  What will happen if we don’t have no-args


constructor in Entity bean?

 Hibernate uses Reflection API to create instance of Entity beans, usually when you call
get() or load() methods. The method Class.newInstance() is used for this and it
requires no-args constructor. So if you won’t have no-args constructor in entity beans,
hibernate will fail to instantiate it and you will get HibernateException.

  What is difference between sorted collection and


ordered collection, 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.

 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.

  What are the collection types in Hibernate?

 There are five collection types in hibernate used for one-to-many relationship
mappings.

1.  Bag
2. Set
3. List
4. Array
5. Map

 How to implement Joins in Hibernate?

 There are various ways to implement joins in hibernate.

  Using associations such as one-to-one, one-to-many etc.


 Using JOIN in the HQL query. There is another form “join fetch” to load associated data
simultaneously, no lazy loading.
 We can fire native sql query and use join keyword.

 Why we should not make Entity Class final?

 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.

  What is HQL and what are it’s benefits?

 Hibernate Framework comes with a powerful object-oriented query language –


Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects
instead of table names, that makes it more close to object oriented programming.

 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.
  What is Query Cache in Hibernate?

 Hibernate implements a cache region for queries resultset that integrates closely with
the hibernate second-level cache.

 This is an optional feature and requires additional steps in code. This is only useful for
queries that are run frequently with the same parameters. 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.


Query query = session.createQuery("from Employee");
query.setCacheable(true);
query.setCacheRegion("ALL_EMP");

  Can we execute native sql query in hibernate?

 Hibernate provide option to execute native SQL queries through the use of SQLQuery
object.

 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.

  What is the benefit of native sql query support in


hibernate?

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

  What is Named SQL Query?

 Hibernate provides Named Query that we can define at a central location and use them
anywhere in the code. We can created named queries for both HQL and Native SQL.

 Hibernate Named Queries can be defined in Hibernate mapping files or through the
use of JPA annotations @NamedQuery and @NamedNativeQuery.

  What are the benefits of Named SQL Query?


 Hibernate Named Query helps us in grouping queries at a central location rather than
letting them scattered all over the code.
Hibernate Named Query syntax is checked when the hibernate session factory is created,
thus making the application fail fast in case of any error in the named queries.
Hibernate Named Query is global, means once defined it can be used throughout the
application.

 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.

  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.

Learn some quick examples at Hibernate Criteria Example.

 How to log hibernate generated sql queries in log


files?

 We can set below property for hibernate configuration to log SQL queries.


<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.

  What is Hibernate Proxy and how it helps in lazy


loading?

 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.

  How to implement relationships in hibernate?

 We can easily implement one-to-one, one-to-many and many-to-many relationships in


hibernate. It can be done using JPA annotations as well as XML based configurations. For
better understanding, you should go through following tutorials.

1.  Hibernate One to One Mapping


2. Hibernate One to Many Mapping
3. Hibernate Many to Many Mapping

 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. For complete example code, you should go through Hibernate
log4j example and Servlet log4j example.

 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/MyLocalD
B</property>

 For a complete example, go through Hibernate JNDI DataSource Example.

  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.AnnotationSessionFac
toryBean 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.

For complete example go through Spring Hibernate Integration and Spring MVC
Hibernate Integration.

 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, a complete example can be found at Hibernate Struts2
Integration Example.

  Which design patterns are used in Hibernate


framework?
 Some of the design patterns used in Hibernate Framework are:

  Domain Model Pattern – An object model of the domain that incorporates both behavior
and data.
 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.
 Proxy Pattern for lazy loading
 Factory pattern in 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. Read more at Hibernate Validation Example.

  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. Learn how to install and use at Hibernate Tools Eclipse Plugin.

Difference between HQL and Criteria Query in Hibernate

 HQL is to perform both select and non-select operations on the data,


but Criteria is only for selecting the data, we cannot perform non-select
operations using criteria
 HQL is suitable for executing Static Queries, where as Criteria is
suitable for executing Dynamic Queries
 HQL doesn’t support pagination concept, but we can achieve
pagination with Criteria
 Criteria used to take more time to execute then HQL
 With Criteria we are safe with SQL Injection because of its dynamic
query generation but in HQL as your queries are either fixed or
parametrized, there is no safe from SQL Injection.

 what is difference between Criterian and Criteria?


Difference between Restrictions and Projections

Hibernate

Restrictions and Projections

First of all, Restrictions and Projections are classes in Hibernate.

Criteria is an interface

Projections is a class which can be used inside setProjection() method.

There are several methods in the Projections.

Restrictions is a class which can be used inside add() method.

There are several methods in the Restrictions.

********

Projections:

Package - org.hibernate.criterion.Projections

The Criteria API provides Projections class.

Projections are used to retrieve the statistical values from the given
criteria class.

We have to use setProjection() method , available for Criteria object to


specify a projection.

We can get the result as List.

You can apply a projection to a query by calling setProjection().

Projections have several methods ..

min() - minimum value

max() - maximum value

sum() - total(sum of all) row value


avg() - average value

count() - total count value

rowCount - total row count

id - retrievs the id from the table

Check the below example -

1. Criteria crt1 =session.createCriteria(Employee.class);


2. crt1.setProjection(Projections.min("age"));
3. List pl=crt1.list();
4. System.out.println("List---min value -"+pl);
This list results the minimum value of age from the Employee table.

1. crt1.setProjection(Projections.max("salary"));
2. crt1.setProjection(Projections.sum("max_client"));
3. crt1.setProjection(Projections.avg("ssid_id"));
4. crt1.setProjection(Projections.count("power_constraint"));
5. crt1.setProjection(Projections.rowCount());
6. crt1.setProjection(http://Projections.id());
Still, there are many methods in Projections.

Projections and Projection are different.

******

Restrictions:

Package - org.hibernate.criterion.Restrictions

Add a restriction to constrain the results to be retrieved.

Restrictions are nothing but, applying certain conditions to retrieve the


data from the table. It is similar to where clause in SQL.

You can use add() method available for Criteria object to add restriction
for a criteria query.

The final values will be displayed, based upon the criteria provided in the
restriction.

We can get the result as List.

First we need to create the criteria and the class name.

1. Criteria crt=session.createCriteria(Employee.class);
This list results the names from the employee table which are not equal
to the name 'nikhil';
Adding the restriction , ne to the criteria, by passing the parameters.

First parameter is the column name.

Second parameter is the value, to check.

We can get the size from the list.

1. Criteria crt=session.createCriteria(Employee.class);
2. crt.add(http://Restrictions.ne("employee_name","nikhil"));
3. List<Employee> crilist=(crt.list());
4. System.out.println("Dispalying list"+crilist);
5. System.out.println("Dispalying size"+crilist.size());
This list results the names from the employee table which are equal to
the name 'teja';

1. crt.add(Restrictions.eq("employee_name","teja"));
2. List<Employee> creqlist=crt.list();
3. System.out.println("Displaying the size--"+creqlist.size());
We can display the results using for each loop from the list.

1. for(Employee emp:creqlist){
2. System.out.println("Results of the restrictions");
3. System.out.println("\n\n\n"+emp.getEmployee_name());
4. }
There are so many methods in restrictions ..

eq() - equal

ne() - not equal

isNull() - Null

isNotNull() - not null

lt() - less than

le ()- less than or equal

gt ()- greater than

ge () - greater than or equal

Example-

1. crt.add(Restrictions.isNotNull("employee_name"));
2. crt.add(Restrictions.isNull("employee_name"));
3. crt.add(Restrictions.le("salary", 25000));
4. crt.add(Restrictions.lt("salary", 45745));
5. crt.add(Restrictions.ge("salary", 50965));
6. crt.add(Restrictions.gt("salary", 50111));
-----------------------------------------------------------
We can also use combination of restrictions and projections together.

We can use multiple restrictions.

We can use multiple projections

How to Configure composite key?

A composite primary key is mapped using an Embeddable type in


hibernate. We’ll first create an Embeddable type
called EmployeeIdentity containing the employeeId and companyId
fields, and then create the Employee entity which will embed
the EmployeeIdentity type.

@Embeddable

public class EmployeeIdentity implements Serializable {

@Entity

@Table(name = "employees")

public class Employee {

@EmbeddedId

private EmployeeIdentity employeeIdentity;

Senario 2:

Define the primary key of the B entity as composite key containing col_a, col_b,
and col_c and what was supposed to be the primary key in the first place, define as
unique constraint. The disadvantage is that the column col_c is not really
conceptually a part of primary key.
@Entity
class A {
@Id
private int b;
@Id
private int c;
}

@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = { "a", "b" }) })
class B {
@Id
private int a;

@Id
@ManyToOne(optional = false)
@JoinColumns(value = {
@JoinColumn(name = "b", referencedColumnName = "b"),
@JoinColumn(name = "c", referencedColumnName = "c") })
private A entityA;
}

Native SQL Query in Hibernate?

 By using Native SQL, we can perform both select, non-select operations


on the data
 In face Native SQL means using the direct SQL command specific to the
particular (current using) database and executing it with using
hibernate

Advantages and Disadvantages of Native SQL

 We can use the database specific keywords (commands), to get the


data from the database
 While migrating a JDBC program into hibernate, the task becomes very
simple because JDBC uses direct SQL commands and hibernate also
supports the same commands by using this Native SQL
 The main draw back of Native SQL is, some times it makes the
hibernate application as database dependent one

How many tables required for Many to Many relationship?

Three tables required. Many-to-Many mapping is usually implemented in database


using a Join Table. For example we can have Cart and Item table

and Cart_Items table for many-to-many mapping. Every cart can have multiple items

and every item can be part of multiple carts, so we have a many to many mapping here.

Hibernate Eager vs Lazy Fetch Type


The relationships are defined through joins in database. Hibernate represents
joins in the form of associations like One-to-One, One-to-Many and Many-to-One.
It is required to define Fetch Type when you use any of these associations. Fetch
Type decides on whether or not to load all the data belongs to associations as
soon as you fetch data from parent table. Fetch type supports two types of
loading: Lazy and Eager. By default, Fetch type would be Lazy.

FetchType.LAZY: It fetches the child entities lazily, that is, at the time of
fetching parent entity it just fetches proxy (created by cglib or any other utility)
of the child entities and when you access any property of child entity then it is
actually fetched by hibernate.

FetchType.EAGER: it fetches the child entities along with parent.

Lazy initialization improves performance by avoiding unnecessary computation


and reduce memory requirements.

Eager initialization takes more memory consumption and processing speed is


slow.

How to configure Bi Directional Relationship?

 we are writing one new attribute inverse=”true” , means we are


intimating to hibernate that we are doing Bi Directional operation
 But default value of inverse=”false“

How to enable logging (log4j) in Hibernate?


Logging is an important step in our application development. This enable us to
debug our code and identify the code execution. The log4j librery is a most
popular logging framework. In this page, we will see how to enable logging using
Log4j framework in Hibernate.

As a first step, add slf4j-log4j12 into your pom.xml file

Hibernate Cascade Options – Cascade Attribute In Hibernate

Cascade attribute is mandatory, when ever we apply relationship between

objects, cascade attribute transfers operations done on one object onto its

related child objects

If we write cascade = “all” then changes at parent class object will be effected to

child class object too, if we write cascade = “all” then all operations

like insert, delete, update at parent object will be effected to child object also

Example: if we apply insert(or update or delete) operation on parent class object,

then child class objects will also be stored into the database.

default value of cascade =”none” means no operations will be transfers to the

child class

Example: if we apply insert(or update or delete) operation on parent class object,

then child class objects will not be effected, if cascade = “none”

Cascade having the values…….

 none (default)
 save
 update
 save-update
 delete
 all
 all-delete-orphan

what is orphan record ..?

an orphan record means it is a record in child table but it doesn’t


have association with its parent in the application.

[ And ]

In an application, if a child record is removed from the collection


and if we want to remove that child record immediately from the
database, then we need to set the cascade =”all-delete-orphan”
And that’s it about this cascade attribute in hibernate, hope i
explained all the values..!!

Difference between List,Set,Map and bag?

List in collection:
A List represents an ordered or sequenced group of elements. It may contain duplicate
elements.

Note: Elements can be inserted or retrieved by their position in


the list. Position or index value starts from 0. List interface
defines its own methods in addition to the methods of
collection interface.

Set in collection:
A set represents a group of elements which can’t contain a duplicate element.

Set mapping:
If an entity has a set of values for a property then this property can be mapped by using
<set> element. A set is initialized with java.util.HashSet.
Bag in collection:
A bag is a java collection which can contain duplicate elements without caring about
sequence element. We can get the information like the number of times an object appears in
the collection by using bag.
Bag works like a list without index (you don’t know what is the order of
elements), so it’s similar to Set with duplicates.

1. In case of list sequence element is needed. In case of bag


no need of sequence element.
When to use Bag

Bags are useful when you add an element to an uninitialized


big collection, it avoids the collection to be loaded.

Map in collection:
A map represents an object with key value pair. A map cannot contain duplicate keys and
one key can map to at most one value.

Map mapping:
If an entity has a map of values for a property then this property can be mapped by using
<map> element. A map is initialized with java.util.HashMap.

How to configure primary key in relationship?


Using @Id Annotaion we can configure Primary key.
Ex:-
@Entity
@Table(name = "user", schema = "test")
public class User {
/* Data Fields */
private int userid;
private String username;
private String password;

public User() { }

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "userid", unique = true, nullable = false)
public Integer getUserid() {
return this.userid;
}
}
How many types of inheritances in hibernate?
We can map the inheritance hierarchy classes with the table of the database. There
are three inheritance mapping strategies defined in the hibernate:

1. Table Per Hierarchy


2. Table Per Concrete class
3. Table Per Subclass

Table Per Hierarchy

In table per hierarchy mapping, single table is required to map the whole hierarchy,
an extra column (known as discriminator column) is added to identify the class. But
nullable values are stored in the table .

Hibernate Table Per Hierarchy using


Annotation
In the previous page, we have mapped the inheritance hierarchy with one table using
xml file. Here, we are going to perform this task using annotation. You need to use
@Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and
@DiscriminatorValue annotations for mapping table per hierarchy strategy.

In case of table per hierarchy, only one table is required to map the inheritance
hierarchy. Here, an extra column (also known as discriminator column) is created
in the table to identify the class.

Let's see the inheritance hierarchy:


There are three classes in this hierarchy. Employee is the super class for
Regular_Employee and Contract_Employee classes.

The table structure for this hierarchy is as shown below:

Example of Hibernate Table Per Hierarchy using


Annotation
1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create
the three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name = "employee101")
6. @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
7. @DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
8. @DiscriminatorValue(value="employee")
9.
10. public class Employee {
11. @Id
12. @GeneratedValue(strategy=GenerationType.AUTO)
13.
14. @Column(name = "id")
15. private int id;
16.
17. @Column(name = "name")
18. private String name;
19.
20. //setters and getters
21. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @DiscriminatorValue("regularemployee")
7. public class Regular_Employee extends Employee{
8.
9. @Column(name="salary")
10. private float salary;
11.
12. @Column(name="bonus")
13. private int bonus;
14.
15. //setters and getters
16. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.Column;
4. import javax.persistence.DiscriminatorValue;
5. import javax.persistence.Entity;
6.
7. @Entity
8. @DiscriminatorValue("contractemployee")
9. public class Contract_Employee extends Employee{
10.
11. @Column(name="pay_per_hour")
12. private float pay_per_hour;
13.
14. @Column(name="contract_duration")
15. private String contract_duration;
16.
17. //setters and getters
18. }

Table Per Concrete class

In case of table per concrete class, tables are created as per class. But duplicate
column is added in subclass tables.

Table Per Concrete class using Annotation


1. Table Per Concrete class using annotation

In case of Table Per Concrete class, tables are created per class. So there are no
nullable values in the table. Disadvantage of this approach is that duplicate columns
are created in the subclass tables.

Here, we need to use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)


annotation in the parent class and @AttributeOverrides annotation in the subclasses.

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) specifies that we


are using table per concrete class strategy. It should be specified in the parent class
only.

@AttributeOverrides defines that parent class attributes will be overriden in this


class. In table structure, parent class table columns will be added in the subclass
table.

The class hierarchy is given below:


The table structure for each table will be as follows:

Table structure for Employee class

Table structure for Regular_Employee class


Table structure for Contract_Employee class

Example of Table per concrete class


In this example we are creating the three classes and provide mapping of these
classes in the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create
the three classes for the above hierarchy:

File: Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name = "employee102")
6. @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
7.
8. public class Employee {
9. @Id
10. @GeneratedValue(strategy=GenerationType.AUTO)
11.
12. @Column(name = "id")
13. private int id;
14.
15. @Column(name = "name")
16. private String name;
17.
18. //setters and getters
19. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name="regularemployee102")
6. @AttributeOverrides({
7. @AttributeOverride(name="id", column=@Column(name="id")),
8. @AttributeOverride(name="name", column=@Column(name="name"))
9. })
10. public class Regular_Employee extends Employee{
11.
12. @Column(name="salary")
13. private float salary;
14.
15. @Column(name="bonus")
16. private int bonus;
17.
18. //setters and getters
19. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3. @Entity
4. @Table(name="contractemployee102")
5. @AttributeOverrides({
6. @AttributeOverride(name="id", column=@Column(name="id")),
7. @AttributeOverride(name="name", column=@Column(name="name"))
8. })
9. public class Contract_Employee extends Employee{
10.
11. @Column(name="pay_per_hour")
12. private float pay_per_hour;
13.
14. @Column(name="contract_duration")
15. private String contract_duration;
16.
17. public float getPay_per_hour() {
18. return pay_per_hour;
19. }
20. public void setPay_per_hour(float payPerHour) {
21. pay_per_hour = payPerHour;
22. }
23. public String getContract_duration() {
24. return contract_duration;
25. }
26. public void setContract_duration(String contractDuration) {
27. contract_duration = contractDuration;
28. }
29. }

Table Per Subclass

In this strategy, tables are created as per class but related by foreign key. So there
are no duplicate columns.

Table Per Subclass using Annotation


1. Table Per Subclass class
2. Example of Table Per Subclass

As we have specified earlier, in case of table per subclass strategy, tables are created
as per persistent classes but they are treated using primary and foreign key. So there
will not be any duplicate column in the relation.

We need to specify @Inheritance(strategy=InheritanceType.JOINED) in the


parent class and @PrimaryKeyJoinColumn annotation in the subclasses.

Let's see the hierarchy of classes that we are going to map.


The table structure for each table will be as follows:

Table structure for Employee class

Table structure for Regular_Employee class


Table structure for Contract_Employee class

Example of Table per subclass class using


Annotation
In this example we are creating the three classes and provide mapping of these
classes in the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create
the three classes for the above hierarchy:

File: Employee.java
1. package com.javatpoint.mypackage;
2. import javax.persistence.*;
3.
4. @Entity
5. @Table(name = "employee103")
6. @Inheritance(strategy=InheritanceType.JOINED)
7.
8. public class Employee {
9. @Id
10. @GeneratedValue(strategy=GenerationType.AUTO)
11.
12. @Column(name = "id")
13. private int id;
14.
15. @Column(name = "name")
16. private String name;
17.
18. //setters and getters
19. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="regularemployee103")
7. @PrimaryKeyJoinColumn(name="ID")
8. public class Regular_Employee extends Employee{
9.
10. @Column(name="salary")
11. private float salary;
12.
13. @Column(name="bonus")
14. private int bonus;
15.
16. //setters and getters
17. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.*;
4.
5. @Entity
6. @Table(name="contractemployee103")
7. @PrimaryKeyJoinColumn(name="ID")
8. public class Contract_Employee extends Employee{
9.
10. @Column(name="pay_per_hour")
11. private float pay_per_hour;
12.
13. @Column(name="contract_duration")
14. private String contract_duration;
15.
16. //setters and getters
17. }

Table per subclass(Join


Criteria Single Table Strategy) Table per Class
 Data not
normalized.  One table for
 Constraint for each concrete
mandatory class.
columns to be not  Not
nullable cannot maintainable.
applied.  Change in base
 Change in any class leads to
subclass leads to  Normalized. changes in all
Table change in structure  Mandatory column tables of
Support of Table constraint can be applied derived class

Discriminat
or Column Present Absent Absent

Joins among table. For example


simple SELECT. All data fetching FourWheeler will
is in one table. Using require a join on FourWheeler
discriminator type, and Vehicle table. If all user
Retrieving individual types can be needs to be fetched than it will Separate Select or
data selected put a join for all three tables Union Select

Multiple. For Vehicle type one


insert on Vehicle table. For
Updating FourWheeler type one insert on
and Single INSERT or Vehicle table and another on One insert or update
Inserting UPDATE FourWheeler table. for each subclass

JPA Support Mandatory Optional

Hibernate Versionless Optimistic Locking


This article is about a Hibernate feature called versionless optimistic locking. Versionless
optimistic locking is an alternative to using JPA’s @Version annotation with a numeric or
timestamp column. It can be used to lower the risk of optimistic locking exceptions.

The @OptimisticLocking Annotation

Optimistic locking with Hibernate is commonly implemented by applying


the @Version annotation to a version instance variable resulting in a VERSION column
with either a numberic value or a timestamp (depending on the declared type of the
instance variable).

Although this is sufficient in many situations, Hibernate does provide alternative locking
strategies too. By applying the @OptimisticLocking annotation on type level you can
define the style of optimistic locking to be applied to a JPA entity.
import org.hibernate.annotations.OptimisticLocking;
import org.hibernate.annotations.OptimisticLockType;
@Entity
@OptimisticLocking(type = OptimisticLockType.VERSION)
@Getter
@Setter
public class Car {

@Id
private Integer id;

@Version
private Integer version;

The example above shows the default locking strategy. When having a look at
the OptimisticLockType (JavaDoc) enumeration, we can see the following locking
strategies:

 ALL
 DIRTY
 NONE
 VERSION

ALL and DIRTY define so-called versionless locking strategies.

If OptimisticLockType.ALL is given in the @OptimisticLocking#type attribute, the


optimistic lockingn strategy works as follows: whenever an UPDATE or DELETE statement
is generated by Hibernate, it will append not only the @Id column in its WHEREclause but
also all of the persistent fields.

Let’s say our Car class would look like


import org.hibernate.annotations.OptimisticLocking;
import org.hibernate.annotations.OptimisticLockType;

@Entity
@OptimisticLocking(type = OptimisticLockType.ALL)
@Getter
@Setter
public class Car {

@Id
private Integer id;

private String model;

private String brand;


}

let us consider we have an already persisted Car instance and we would change
property model
Car car = carRepository.findOne(carId);
car.setModel("Punto");

car = carRepository.save(car);

with OptimisticLockType.ALL the generated SQL statement would be


UPDATE CAR SET MODEL = ?, BRAND = ? WHERE ID = ? AND MODEL = ? AND BRAND = ?
All columns of the associated database row are used in the WHERE clause. If
the Car instance would have been changed in the meantime and the UPDATE would not
find a row, a StaleStateException or an OptimisticLockException is going be thrown.

With OptimisticLockType.DIRTY only the dirty/changed fields (in our case model) would
be part of the SQL statement
UPDATE CAR SET MODEL = ?, BRAND = ? WHERE ID = ? AND MODEL = ?

If the model column still has the same value the UPDATE will succeed.

With such an optimistic locking strategy, the main advantage is that it reduces the
potential of overlapping updates. When using OptimisticLockType.DIRTY, the
documentation advises to use the @DynamicUpdate and @SelectBeforeUpdate annotations
in combination with @OptimisticLocking. @DynamicUpdate will
generate UPDATE statements only SETting the dirty columns, @SelectBeforeUpdate will
avoid issues with detached entities, assuming the Hibernate session is opened for the
entire request.

Hibernate Transaction Management


Example
1. Understanding Transaction
2. ACID Property
3. Hibernate Transaction Management

A transaction simply represents a unit of work. In such case, if one step fails, the
whole transaction fails (which is termed as atomicity). A transaction can be described
by ACID properties (Atomicity, Consistency, Isolation and Durability).
Transaction Interface in Hibernate
In hibernate framework, we have Transaction interface that defines the unit of work.
It maintains abstraction from the transaction implementation (JTA,JDBC).

A transaction is associated with Session and instantiated by


calling session.beginTransaction().

The methods of Transaction interface are as follows:

1. void begin() starts a new transaction.


2. void commit() ends the unit of work unless we are in FlushMode.NEVER.
3. void rollback() forces this transaction to rollback.
4. void setTimeout(int seconds) it sets a transaction timeout for any
transaction started by a subsequent call to begin on this instance.
5. boolean isAlive() checks if the transaction is still alive.
6. void registerSynchronization(Synchronization s) registers a user
synchronization callback for this transaction.
7. boolean wasCommited() checks if the transaction is commited successfully.
8. boolean wasRolledBack() checks if the transaction is rolledback
successfully.

What is @Temparal annotation?

We can use the @Temporal annotation to specify the precision in which


hibernate will save the date, time or timestamp. In the following java
class we show you each type. If you’re interested in how these types will
be saved in the database, you can immediately scroll to the bottom of
the page to see the result.
 TemporalType.DATE : maps the date as java.sql.Date .
 TemporalType.TIME : maps the date as java.sql.Time .
 TemporalType.TIMESTAMP : maps the date as java.sql.Timestamp .

You might also like