SlideShare una empresa de Scribd logo
1 de 45
HIBERNATE ORM
(Object Relational Model)
CREATED BY : SOURABH AGGARWAL
CREATED ON : 02 JULY 2015
Hibernate Modules
● Hibernate ORM
● Hibernate Search
● Hibernate Validator
● Hibernate OGM
● Hibernate Tools
● Others
Why we use hibernate?
● Hibernate supports Inheritance, Associations, Collections.
● In hibernate if we save the derived class object, then its base class object will also be stored into the database, it means hibernate
supporting inheritance
● Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
● This will also supports collections like List,Set,Map (Only new collections)
● In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked
exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate we have the translator which converts checked
to Un-checked ;)
● Hibernate has capability to generate primary keys automatically while we are storing the records into database
● Hibernate has its own query language, i.e hibernate query language which is database independent
● So if we change the database, then also our application will works as HQL is database independent
● HQL contains database independent commands
● While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and
throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us ;)
● Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by
using this caching technique an application performance will be increased automatically.
● Hibernate supports annotations, apart from XML
● Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.
● Getting pagination in hibernate is quite simple.
Hibernate ORM
● Version : 4.3.9
● Object/Relational Mapping
● JPA Provider
Hibernate Architecture
Interfaces In Hibernate
● Session Interface : The basic interface for all hibernate applications. The instances are
light weighted and can be created and destroyed without expensive process.
● SessionFactory interface : The delivery of session objects to hibernate applications is
done by this interface. For the whole application, there will be generally one
SessionFactory and can be shared by all the application threads.
● Configuration Interface : Hibernate bootstrap action is configured by this interface. The
location specification is specified by specific mapping documents, is done by the instance
of this interface.
● Transaction Interface : This is an optional interface. This interface is used to abstract
the code from a transaction that is implemented such as a JDBC / JTA transaction.
● Query and Criteria interface : The queries from the user are allowed by this interface
apart from controlling the flow of the query execution.
Creating SessionFactory
● Hibernate provides different options to create a SessionFactory instance.
SessionFactory is used for creating multiple lightweight instances of
Session object, which in turn enables database operations. We need not
worry about the performance side of creating/destroying those Hibernate
Session instances because they’re lightweight components.
● On the other side the process of creating instance for Hibernate
SessionFactory is an expensive operation. So we need to exercise
caution while instantiating Hibernate SessionFactory. We can choose to
create the instance through a singleton design pattern.
SessionFactory Configurations
● Database connection settings : These attributes comprises the driver class, url of jdbc connection,
username and password for connected schema.
● Hibernate Dialect : As we know, Hibernate is database-agnostic framework, at some point, hibernate
needs to use database specific, extended or native SQL, so hibernate uses dialect configuration to
know which database you’re using so that it can switch to the database specific SQL generator code. If
you’ve omitted this entry, hibernate would provide default one based on the database driver provided.
● Hibernate Session Context : Tracking of session against different contexts can help achieve Create,
Read, Update and Delete operations. Mainly, permitted values are Thread or its corresponding class or
JTA for managed container or its corresponding class. Transaction demarcation concept and all of
these different context are to be discussed later.
Properties Of SessionFactory
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/Hibernate_Training</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property
name="net.sf.ehcache.configurationResourceName">/com/xebia/training/hibernate/orm/session_factory/resourc
es/myehcache.xml</property>
Methods?
● getSessionFactoryOptions()
●
withOptions()
● openSession()
●
getCurrentSession()
● withStatelessOptions()
● openStatelessSession()
●
openStatelessSession(Connection)
● getClassMetadata(Class)
●
getClassMetadata(String)
● getCollectionMetadata(String)
● getAllClassMetadata()
●
getAllCollectionMetadata()
● GetStatistics()
●
close()
● isClosed()
●
getCache()
● evict(Class)
●
evict(Class, Serializable)
● evictEntity(String)
● evictEntity(String, Serializable)
●
evictCollection(String)
● evictCollection(String, Serializable)
●
evictQueries(String)
● evictQueries()
● getDefinedFilterNames()
●
getFilterDefinition(String)
● containsFetchProfileDefinition(String)
●
getTypeHelper()
Configure Hibernate with
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/Hibernate_Training</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property
name="net.sf.ehcache.configurationResourceName">/com/xebia/training/hibernate/orm/session_factory/resources/myehcache.xml</property>
</session-factory>
</hibernate-configuration>
Hibernate Session
Hibernate SessionFactory is the factory class
through which we get sessions and perform
database operations. Hibernate SessionFactory
provides three methods through which we can
get Session object –
● GetCurrentSession().
● OpenSession().
● openStatelessSession().
Hibernate 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 like below.
● <property name="hibernate.current_session_context_class">thread</property>
● If its not configured to thread, then we will get below exception.
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured! at
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) at
com.xebia.training.hibernate.orm.criteria.main.HibernateSessionExample.main(HibernateSessionExample.java:16)
●
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. Hibernate Session objects are not thread safe, so we should not use it in multi-threaded
environment. We can use it in single threaded environment because it’s relatively faster than opening a new session.
Hibernate openSession()?
● 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. For web
application frameworks, we can choose to open
a new session for each request or for each
session based on the requirement.
●
Hibernate 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 like below.
● <property name="hibernate.current_session_context_class">thread</property>
●
Opne Transaction is needed for any operations.
● If its not configured to thread, then we will get below exception.
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) at
com.xebia.training.hibernate.orm.criteria.main.HibernateSessionExample.main(HibernateSessionExa
mple.java:16)
●
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. Hibernate Session objects are not thread safe, so we
should not use it in multi-threaded environment. We can use it in single threaded environment because
it’s relatively faster than opening a new session.
Hibernate openStatelessSession()?
●
Hibernate SessionFactory openStatelessSession() method returns instance of
StatelessSession. There is another overloaded method where we can pass
java.sql.Connection object to get a stateless session object from hibernate.
●
StatelessSession does not implement first-level cache and it doesn’t interact with any second-
level cache. Since it’s stateless, it doesn’t implement transactional write-behind or automatic
dirty checking or do cascading operations to associated entities.
● Collections are also ignored by a stateless session. Operations performed via a stateless
session bypass Hibernate’s event model and interceptors. It’s more like a normal JDBC
connection and doesn’t provide any benefits that come from using hibernate framework.
●
However, stateless session can be a good fit in certain situations, for example where we are
loading bulk data into database and we don’t want hibernate session to hold huge data in first-
level cache memory.
Transaction
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).
● AbstractTransactionImpl.java implments TransactionImplemento.java which extends Transaction interface.
– JtaTransaction.java
– JdbcTransaction.java
– CMTTransaction.java
● A transaction is associated with Session and instantiated by calling session.beginTransaction().
● The methods of Transaction interface are as follows:
– void begin() starts a new transaction.
– void commit() ends the unit of work unless we are in FlushMode.NEVER.
– void rollback() forces this transaction to rollback.
– void setTimeout(int seconds) it sets a transaction timeout for any transaction started by a subsequent call to begin on this
instance.
– boolean isAlive() checks if the transaction is still alive.
– void registerSynchronization(Synchronization s) registers a user synchronization callback for this transaction.
– boolean wasCommited() checks if the transaction is commited successfully.
– boolean wasRolledBack() checks if the transaction is rolledback successfully.
Hibernate And JPA
● Hibernate with JPA is used for mapping entities or table
together to form a realtionship between those entities.
● We have four type of association we are going to use
and dicuss between entities:
● @OneToOne
● @OneToMany
● @ManyToMany
● @ManyToOne
@ManyToOne or @OneToMany
● @ManyToOne annotation defines a single-
valued association to another entity class that
has many-to-one multiplicity. It is not normally
necessary to specify the target entity explicitly
since it can usually be inferred from the type of
the object being referenced.
● @JoinColumn is used to specify a mapped
column for joining an entity association.
@OneToOne
● @OneToOne annotation defines a single-
valued association to another entity class that
has one-to-one multiplicity. It is not normally
necessary to specify the target entity explicitly
since it can usually be inferred from the type of
the object being referenced.
● @JoinColumn is used to specify a mapped
column for joining an entity association.
@ManyToMany
● @ManyToOne annotation defines a muti-valued
association to another entity class that has
many-to-many multiplicity. It is not normally
necessary to specify the target entity explicitly
since it can usually be inferred from the type of
the object being referenced.
● @JoinTable is used to specify a mapped table
for joining an entity association.
Get() and Load() functions?
● Hibernate Session provide different methods to fetch data from database.
Two of them are – get() and load(). There are also a lot of overloaded
methods for these, that we can use in different circumstances.
● At first look both get() and load() seems similar because both of them fetch
the data from database, however there are few differences between them,
let’s look at them with a simple example.
● From the output in the below program it’s clear that get() returns the object
by fetching it from database or from hibernate cache whereas load() just
returns the reference of an object that might not actually exists, it loads the
data from database or cache only when you access other properties of the
object.
get() Vs load() Example?
public class HibernateGetVsLoad {
public static void main(String[] args) {
//Prep Work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//Get Example
Employee emp = (Employee) session.get(Employee.class, new Long(2));
System.out.println("Employee get called");
System.out.println("Employee ID= "+emp.getId());
System.out.println("Employee Get Details:: "+emp+"n");
//load Example
Employee emp1 = (Employee) session.load(Employee.class, new Long(1));
System.out.println("Employee load called");
System.out.println("Employee ID= "+emp1.getId());
System.out.println("Employee load Details:: "+emp1+"n");
//Close resources
tx.commit();
sessionFactory.close();
}
}
Output
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_,
employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as
address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE
employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where
employee0_.emp_id=?
Employee get called
Employee ID= 2
Employee Get Details:: com.xebia.training.hibernate.orm.get_vs_load.model.Employee@2d35da43
Employee load called
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_,
employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as
address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE
employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where
employee0_.emp_id=?
Employee ID= 1
Employee load Details:: com.xebia.training.hibernate.orm.get_vs_load.model.Employee@18f2225f
● From the output it’s clear that get() returns the object by fetching it from database or from hibernate cache
whereas load() just returns the reference of an object that might not actually exists, it loads the data from database
or cache only when you access other properties of the object.
NoData found for get() and load()
//Get Example
try{
Employee emp = (Employee) session.get(Employee.class, new Long(200));
System.out.println("Employee get called");
if(emp != null){
System.out.println("Employee GET ID= "+emp.getId());
System.out.println("Employee Get Details:: "+emp+"n");
}
}catch(Exception e){
e.printStackTrace();
}
//load Example
try{
Employee emp1 = (Employee) session.load(Employee.class, new Long(100));
System.out.println("Employee load called");
System.out.println("Employee LOAD ID= "+emp1.getId());
System.out.println("Employee load Details:: "+emp1+"n");
}catch(Exception e){
e.printStackTrace();
}
Output
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary
as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as
city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on
employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
Employee get called
Employee load called
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary
as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as
city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on
employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
[com.xebia.training.hibernate.orm.get_vs_load.model.Employee#100]
at org.hibernate.internal.SessionFactoryImpl$1$1.handleEntityNotFound(SessionFactoryImpl.java:253)
at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.xebia.training.hibernate.orm.get_vs_load.model.Employee_$$_jvst515_1.getId(Employee_$$_jvst515_1.java)
at
com.xebia.training.hibernate.orm.get_vs_load.main.GetVsLoadNoDataInDBExample.main(GetVsLoadNoDataInDBExample.java:3
5)
Overloaded methods
Let’s look at some of the overloaded methods too. Above get() and load()
methods could have been written as below too.
● Employee emp = (Employee)
session.get("com.journaldev.hibernate.model.Employee", new Long(2));
● Employee emp1 = (Employee)
session.load("com.journaldev.hibernate.model.Employee", new Long(1));
● Employee emp2 = new Employee();
session.load(emp1, new Long(1));
There are other methods with LockOptions argument but I haven’t used them.
Notice that we need to pass full class name as argument.
Differences between get() vs load()
● 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.
● Since load() throws exception when data is not
found, we should use it only when we know data
exists.
● We should use get() when we want to make sure
data exists in the database.
Hibernate Operations
● Save
● Update
● Get
● fetch
SQL/HQL Queries
● 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.
Clauses in HQL
● From Clause: It’s same as select clause in SQL, from Employee is same as select
* from Employee. We can also create alias such as from Employee emp or from
Employee as emp.
● Join Clause: HQL supports inner join, left outer join, right outer join and full join. For
example, select e.name, a.city from Employee e INNER JOIN e.address a. In this
query, Employee class should have a variable named address. We will look into it
in the example code.
● Aggregate Functions: HQL supports commonly used aggregate functions such as
count(*), count(distinct x), min(), max(), avg() and sum().
●
Expressions: HQL supports arithmetic expressions (+, -, *, /), binary comparison
operators (=, >=, <=, <>, !=, like), logical operations (and, or, not) etc.
● HQL also supports ordre by and group by clauses.
● HQL also supports sub-queries just like SQL queries.
● HQL supports DDL, DML and executing store procedures too.
Lazy/Eager Loading
Proxy objects
Caching In Hibernate
L1 Cache
L2 Cache
Currently EHCache and Infinispan
Concurrency Strategy
● Transactional: Use this strategy for read-mostly data where it is critical to prevent stale
data in concurrent transactions,in the rare case of an update.
● Read-write: Again use this strategy for read-mostly data where it is critical to prevent
stale data in concurrent transactions,in the rare case of an update.
● Nonstrict-read-write: This strategy makes no guarantee of consistency between the
cache and the database. Use this strategy if data hardly ever changes and a small
likelihood of stale data is not of critical concern.
● Read-only: A concurrency strategy suitable for data which never changes. Use it for
reference data only
Dependencies
● Hibernate-core : 4.3.5.Final : Hibernate Core
API.
● Mysql-connector-java : 5.0.5 : MySQL Driver.
● Ehcache-core : 2.6.9 : EHCache Core APIs.
● Hibernate-ehcache : 4.3.5.Final : Hibernate
EHCache API.
● Slf4j-simple : 1.7.5 : EHCache uses slf4j for
logging.
SessionFactory Configuration
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">pankaj123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
<property name="hibernate.connection.username">pankaj</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- For singleton factory -->
<!-- <property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prope
rty>-->
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
<mapping class="com.journaldev.hibernate.model.Employee" />
<mapping class="com.journaldev.hibernate.model.Address" />
</session-factory>
Configuration Parameter
● hibernate.cache.region.factory_class is used to define the Factory class for Second
level caching, I am using org.hibernate.cache.ehcache.EhCacheRegionFactory for this.
If you want the factory class to be singleton, you should use
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory class.
If you are using Hibernate 3, corresponding classes will be
net.sf.ehcache.hibernate.EhCacheRegionFactory and
net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory.
● hibernate.cache.use_second_level_cache is used to enable the second level cache.
● hibernate.cache.use_query_cache is used to enable the query cache, without it HQL
queries results will not be cached.
● net.sf.ehcache.configurationResourceName is used to define the EHCache
configuration file location, it’s an optional parameter and if it’s not present EHCache will try
to locate ehcache.xml file in the application classpath.
myehcache.xml
<?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>
Criteria API
● Most of the times, we prefer HQL for querying the database
and getting the results. HQL is not preferred way for updating
or deleting values because then we need to take care of any
associations between tables.
● 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.
Common usage of Criteria API
● 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.
Thank You......

Más contenido relacionado

La actualidad más candente

jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
Ram132
 

La actualidad más candente (20)

Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Jpa
JpaJpa
Jpa
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Java persistence api
Java persistence api Java persistence api
Java persistence api
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Hibernate
HibernateHibernate
Hibernate
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Deployment
DeploymentDeployment
Deployment
 

Similar a Hibernate complete Training

02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
Syed Shahul
 
Hibernate reference1
Hibernate reference1Hibernate reference1
Hibernate reference1
chandra mouli
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
Joe Jacob
 

Similar a Hibernate complete Training (20)

Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Hibernate 1x2
Hibernate 1x2Hibernate 1x2
Hibernate 1x2
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate
HibernateHibernate
Hibernate
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Advance Features of Hibernate
Advance Features of HibernateAdvance Features of Hibernate
Advance Features of Hibernate
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASITLearn HIBERNATE at ASIT
Learn HIBERNATE at ASIT
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Hibernate reference1
Hibernate reference1Hibernate reference1
Hibernate reference1
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 

Más de sourabh aggarwal (6)

Mongo production Sharded cluster
Mongo production Sharded clusterMongo production Sharded cluster
Mongo production Sharded cluster
 
Mule Complete Training
Mule Complete TrainingMule Complete Training
Mule Complete Training
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Liferay with xebia
Liferay with xebiaLiferay with xebia
Liferay with xebia
 

Hibernate complete Training

  • 1. HIBERNATE ORM (Object Relational Model) CREATED BY : SOURABH AGGARWAL CREATED ON : 02 JULY 2015
  • 2. Hibernate Modules ● Hibernate ORM ● Hibernate Search ● Hibernate Validator ● Hibernate OGM ● Hibernate Tools ● Others
  • 3. Why we use hibernate? ● Hibernate supports Inheritance, Associations, Collections. ● In hibernate if we save the derived class object, then its base class object will also be stored into the database, it means hibernate supporting inheritance ● Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One ● This will also supports collections like List,Set,Map (Only new collections) ● In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate we have the translator which converts checked to Un-checked ;) ● Hibernate has capability to generate primary keys automatically while we are storing the records into database ● Hibernate has its own query language, i.e hibernate query language which is database independent ● So if we change the database, then also our application will works as HQL is database independent ● HQL contains database independent commands ● While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us ;) ● Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically. ● Hibernate supports annotations, apart from XML ● Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API. ● Getting pagination in hibernate is quite simple.
  • 4. Hibernate ORM ● Version : 4.3.9 ● Object/Relational Mapping ● JPA Provider
  • 6. Interfaces In Hibernate ● Session Interface : The basic interface for all hibernate applications. The instances are light weighted and can be created and destroyed without expensive process. ● SessionFactory interface : The delivery of session objects to hibernate applications is done by this interface. For the whole application, there will be generally one SessionFactory and can be shared by all the application threads. ● Configuration Interface : Hibernate bootstrap action is configured by this interface. The location specification is specified by specific mapping documents, is done by the instance of this interface. ● Transaction Interface : This is an optional interface. This interface is used to abstract the code from a transaction that is implemented such as a JDBC / JTA transaction. ● Query and Criteria interface : The queries from the user are allowed by this interface apart from controlling the flow of the query execution.
  • 7. Creating SessionFactory ● Hibernate provides different options to create a SessionFactory instance. SessionFactory is used for creating multiple lightweight instances of Session object, which in turn enables database operations. We need not worry about the performance side of creating/destroying those Hibernate Session instances because they’re lightweight components. ● On the other side the process of creating instance for Hibernate SessionFactory is an expensive operation. So we need to exercise caution while instantiating Hibernate SessionFactory. We can choose to create the instance through a singleton design pattern.
  • 8. SessionFactory Configurations ● Database connection settings : These attributes comprises the driver class, url of jdbc connection, username and password for connected schema. ● Hibernate Dialect : As we know, Hibernate is database-agnostic framework, at some point, hibernate needs to use database specific, extended or native SQL, so hibernate uses dialect configuration to know which database you’re using so that it can switch to the database specific SQL generator code. If you’ve omitted this entry, hibernate would provide default one based on the database driver provided. ● Hibernate Session Context : Tracking of session against different contexts can help achieve Create, Read, Update and Delete operations. Mainly, permitted values are Thread or its corresponding class or JTA for managed container or its corresponding class. Transaction demarcation concept and all of these different context are to be discussed later.
  • 9. Properties Of SessionFactory <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/Hibernate_Training</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- enable second level cache and query cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">/com/xebia/training/hibernate/orm/session_factory/resourc es/myehcache.xml</property>
  • 10. Methods? ● getSessionFactoryOptions() ● withOptions() ● openSession() ● getCurrentSession() ● withStatelessOptions() ● openStatelessSession() ● openStatelessSession(Connection) ● getClassMetadata(Class) ● getClassMetadata(String) ● getCollectionMetadata(String) ● getAllClassMetadata() ● getAllCollectionMetadata() ● GetStatistics() ● close() ● isClosed() ● getCache() ● evict(Class) ● evict(Class, Serializable) ● evictEntity(String) ● evictEntity(String, Serializable) ● evictCollection(String) ● evictCollection(String, Serializable) ● evictQueries(String) ● evictQueries() ● getDefinedFilterNames() ● getFilterDefinition(String) ● containsFetchProfileDefinition(String) ● getTypeHelper()
  • 11. Configure Hibernate with hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/Hibernate_Training</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- enable second level cache and query cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">/com/xebia/training/hibernate/orm/session_factory/resources/myehcache.xml</property> </session-factory> </hibernate-configuration>
  • 12. Hibernate Session Hibernate SessionFactory is the factory class through which we get sessions and perform database operations. Hibernate SessionFactory provides three methods through which we can get Session object – ● GetCurrentSession(). ● OpenSession(). ● openStatelessSession().
  • 13. Hibernate 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 like below. ● <property name="hibernate.current_session_context_class">thread</property> ● If its not configured to thread, then we will get below exception. Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured! at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) at com.xebia.training.hibernate.orm.criteria.main.HibernateSessionExample.main(HibernateSessionExample.java:16) ● 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. Hibernate Session objects are not thread safe, so we should not use it in multi-threaded environment. We can use it in single threaded environment because it’s relatively faster than opening a new session.
  • 14. Hibernate openSession()? ● 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. For web application frameworks, we can choose to open a new session for each request or for each session based on the requirement. ●
  • 15. Hibernate 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 like below. ● <property name="hibernate.current_session_context_class">thread</property> ● Opne Transaction is needed for any operations. ● If its not configured to thread, then we will get below exception. Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured! at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) at com.xebia.training.hibernate.orm.criteria.main.HibernateSessionExample.main(HibernateSessionExa mple.java:16) ● 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. Hibernate Session objects are not thread safe, so we should not use it in multi-threaded environment. We can use it in single threaded environment because it’s relatively faster than opening a new session.
  • 16. Hibernate openStatelessSession()? ● Hibernate SessionFactory openStatelessSession() method returns instance of StatelessSession. There is another overloaded method where we can pass java.sql.Connection object to get a stateless session object from hibernate. ● StatelessSession does not implement first-level cache and it doesn’t interact with any second- level cache. Since it’s stateless, it doesn’t implement transactional write-behind or automatic dirty checking or do cascading operations to associated entities. ● Collections are also ignored by a stateless session. Operations performed via a stateless session bypass Hibernate’s event model and interceptors. It’s more like a normal JDBC connection and doesn’t provide any benefits that come from using hibernate framework. ● However, stateless session can be a good fit in certain situations, for example where we are loading bulk data into database and we don’t want hibernate session to hold huge data in first- level cache memory.
  • 17. Transaction 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).
  • 18. 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). ● AbstractTransactionImpl.java implments TransactionImplemento.java which extends Transaction interface. – JtaTransaction.java – JdbcTransaction.java – CMTTransaction.java ● A transaction is associated with Session and instantiated by calling session.beginTransaction(). ● The methods of Transaction interface are as follows: – void begin() starts a new transaction. – void commit() ends the unit of work unless we are in FlushMode.NEVER. – void rollback() forces this transaction to rollback. – void setTimeout(int seconds) it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance. – boolean isAlive() checks if the transaction is still alive. – void registerSynchronization(Synchronization s) registers a user synchronization callback for this transaction. – boolean wasCommited() checks if the transaction is commited successfully. – boolean wasRolledBack() checks if the transaction is rolledback successfully.
  • 19. Hibernate And JPA ● Hibernate with JPA is used for mapping entities or table together to form a realtionship between those entities. ● We have four type of association we are going to use and dicuss between entities: ● @OneToOne ● @OneToMany ● @ManyToMany ● @ManyToOne
  • 20. @ManyToOne or @OneToMany ● @ManyToOne annotation defines a single- valued association to another entity class that has many-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. ● @JoinColumn is used to specify a mapped column for joining an entity association.
  • 21. @OneToOne ● @OneToOne annotation defines a single- valued association to another entity class that has one-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. ● @JoinColumn is used to specify a mapped column for joining an entity association.
  • 22. @ManyToMany ● @ManyToOne annotation defines a muti-valued association to another entity class that has many-to-many multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. ● @JoinTable is used to specify a mapped table for joining an entity association.
  • 23. Get() and Load() functions? ● Hibernate Session provide different methods to fetch data from database. Two of them are – get() and load(). There are also a lot of overloaded methods for these, that we can use in different circumstances. ● At first look both get() and load() seems similar because both of them fetch the data from database, however there are few differences between them, let’s look at them with a simple example. ● From the output in the below program it’s clear that get() returns the object by fetching it from database or from hibernate cache whereas load() just returns the reference of an object that might not actually exists, it loads the data from database or cache only when you access other properties of the object.
  • 24. get() Vs load() Example? public class HibernateGetVsLoad { public static void main(String[] args) { //Prep Work SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); //Get Example Employee emp = (Employee) session.get(Employee.class, new Long(2)); System.out.println("Employee get called"); System.out.println("Employee ID= "+emp.getId()); System.out.println("Employee Get Details:: "+emp+"n"); //load Example Employee emp1 = (Employee) session.load(Employee.class, new Long(1)); System.out.println("Employee load called"); System.out.println("Employee ID= "+emp1.getId()); System.out.println("Employee load Details:: "+emp1+"n"); //Close resources tx.commit(); sessionFactory.close(); } }
  • 25. Output Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? Employee get called Employee ID= 2 Employee Get Details:: com.xebia.training.hibernate.orm.get_vs_load.model.Employee@2d35da43 Employee load called Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? Employee ID= 1 Employee load Details:: com.xebia.training.hibernate.orm.get_vs_load.model.Employee@18f2225f ● From the output it’s clear that get() returns the object by fetching it from database or from hibernate cache whereas load() just returns the reference of an object that might not actually exists, it loads the data from database or cache only when you access other properties of the object.
  • 26. NoData found for get() and load() //Get Example try{ Employee emp = (Employee) session.get(Employee.class, new Long(200)); System.out.println("Employee get called"); if(emp != null){ System.out.println("Employee GET ID= "+emp.getId()); System.out.println("Employee Get Details:: "+emp+"n"); } }catch(Exception e){ e.printStackTrace(); } //load Example try{ Employee emp1 = (Employee) session.load(Employee.class, new Long(100)); System.out.println("Employee load called"); System.out.println("Employee LOAD ID= "+emp1.getId()); System.out.println("Employee load Details:: "+emp1+"n"); }catch(Exception e){ e.printStackTrace(); }
  • 27. Output Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? Employee get called Employee load called Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.xebia.training.hibernate.orm.get_vs_load.model.Employee#100] at org.hibernate.internal.SessionFactoryImpl$1$1.handleEntityNotFound(SessionFactoryImpl.java:253) at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262) at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185) at com.xebia.training.hibernate.orm.get_vs_load.model.Employee_$$_jvst515_1.getId(Employee_$$_jvst515_1.java) at com.xebia.training.hibernate.orm.get_vs_load.main.GetVsLoadNoDataInDBExample.main(GetVsLoadNoDataInDBExample.java:3 5)
  • 28. Overloaded methods Let’s look at some of the overloaded methods too. Above get() and load() methods could have been written as below too. ● Employee emp = (Employee) session.get("com.journaldev.hibernate.model.Employee", new Long(2)); ● Employee emp1 = (Employee) session.load("com.journaldev.hibernate.model.Employee", new Long(1)); ● Employee emp2 = new Employee(); session.load(emp1, new Long(1)); There are other methods with LockOptions argument but I haven’t used them. Notice that we need to pass full class name as argument.
  • 29. Differences between get() vs load() ● 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. ● Since load() throws exception when data is not found, we should use it only when we know data exists. ● We should use get() when we want to make sure data exists in the database.
  • 30. Hibernate Operations ● Save ● Update ● Get ● fetch
  • 31. SQL/HQL Queries ● 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.
  • 32. Clauses in HQL ● From Clause: It’s same as select clause in SQL, from Employee is same as select * from Employee. We can also create alias such as from Employee emp or from Employee as emp. ● Join Clause: HQL supports inner join, left outer join, right outer join and full join. For example, select e.name, a.city from Employee e INNER JOIN e.address a. In this query, Employee class should have a variable named address. We will look into it in the example code. ● Aggregate Functions: HQL supports commonly used aggregate functions such as count(*), count(distinct x), min(), max(), avg() and sum(). ● Expressions: HQL supports arithmetic expressions (+, -, *, /), binary comparison operators (=, >=, <=, <>, !=, like), logical operations (and, or, not) etc. ● HQL also supports ordre by and group by clauses. ● HQL also supports sub-queries just like SQL queries. ● HQL supports DDL, DML and executing store procedures too.
  • 37. L2 Cache Currently EHCache and Infinispan
  • 38. Concurrency Strategy ● Transactional: Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update. ● Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update. ● Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern. ● Read-only: A concurrency strategy suitable for data which never changes. Use it for reference data only
  • 39. Dependencies ● Hibernate-core : 4.3.5.Final : Hibernate Core API. ● Mysql-connector-java : 5.0.5 : MySQL Driver. ● Ehcache-core : 2.6.9 : EHCache Core APIs. ● Hibernate-ehcache : 4.3.5.Final : Hibernate EHCache API. ● Slf4j-simple : 1.7.5 : EHCache uses slf4j for logging.
  • 40. SessionFactory Configuration <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">pankaj123</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property> <property name="hibernate.connection.username">pankaj</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- For singleton factory --> <!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prope rty>--> <!-- enable second level cache and query cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property> <mapping class="com.journaldev.hibernate.model.Employee" /> <mapping class="com.journaldev.hibernate.model.Address" /> </session-factory>
  • 41. Configuration Parameter ● hibernate.cache.region.factory_class is used to define the Factory class for Second level caching, I am using org.hibernate.cache.ehcache.EhCacheRegionFactory for this. If you want the factory class to be singleton, you should use org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory class. If you are using Hibernate 3, corresponding classes will be net.sf.ehcache.hibernate.EhCacheRegionFactory and net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory. ● hibernate.cache.use_second_level_cache is used to enable the second level cache. ● hibernate.cache.use_query_cache is used to enable the query cache, without it HQL queries results will not be cached. ● net.sf.ehcache.configurationResourceName is used to define the EHCache configuration file location, it’s an optional parameter and if it’s not present EHCache will try to locate ehcache.xml file in the application classpath.
  • 42. myehcache.xml <?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>
  • 43. Criteria API ● Most of the times, we prefer HQL for querying the database and getting the results. HQL is not preferred way for updating or deleting values because then we need to take care of any associations between tables. ● 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.
  • 44. Common usage of Criteria API ● 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.