Hibenate
Hibenate
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.
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
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.
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?
EntityNotFoundException: An Entity was expected but did not match the requirement
LazyInitializationException
OptimisticLockException
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.
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.
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.
list() iterate()
1 With one database hit, all the records are loaded For each record, one database
hit is made
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.
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.
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:
Let's see the second level cache implementation and cache usage.
To understand the second level cache through example, we need to follow the following steps:
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)
@Id
public Employee() {}
super();
this.name = name;
this.salary = salary;
this.id = id;
return name;
this.name = name;
return salary;
this.salary = salary;
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>
File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
"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>
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;
StandardServiceRegistry ssr=new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session1=factory.openSession();
Employee emp1=(Employee)session1.load(Employee.class,121);
session1.close();
Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);
session2.close();
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.
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.
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.
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.
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
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;
@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;
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.
Internal state of SessionFactory is immutable, so it’s thread safe. Multiple threads can
access it simultaneously to get Session instances.
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 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</property>
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.
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.
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.
<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="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.
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().
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.
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.
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.
There are five collection types in hibernate used for one-to-many relationship
mappings.
1. Bag
2. Set
3. List
4. Array
5. 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.
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");
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 complete example go through Spring Hibernate Integration and Spring MVC
Hibernate Integration.
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.
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
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
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.
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.
Hibernate
Criteria is an interface
********
Projections:
Package - org.hibernate.criterion.Projections
Projections are used to retrieve the statistical values from the given
criteria class.
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.
******
Restrictions:
Package - org.hibernate.criterion.Restrictions
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.
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.
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
isNull() - Null
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.
@Embeddable
@Entity
@Table(name = "employees")
@EmbeddedId
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;
}
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.
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.
objects, cascade attribute transfers operations done on one object onto its
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
then child class objects will also be stored into the database.
child class
none (default)
save
update
save-update
delete
all
all-delete-orphan
[ And ]
List in collection:
A List represents an ordered or sequenced group of elements. It may contain duplicate
elements.
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.
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.
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:
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 .
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.
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. }
In case of table per concrete class, tables are created as per class. But duplicate
column is added in subclass tables.
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.
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. }
In this strategy, tables are created as per class but related by foreign key. So there
are no duplicate columns.
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.
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. }
Discriminat
or Column Present Absent Absent
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
@Entity
@OptimisticLocking(type = OptimisticLockType.ALL)
@Getter
@Setter
public class Car {
@Id
private Integer id;
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.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.
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).