Hibernate - ORM Technology For Java: Shantha Lakshmi (JCOE Team) 16/07/2008
Hibernate - ORM Technology For Java: Shantha Lakshmi (JCOE Team) 16/07/2008
December 7, 2021 2
Persistence Technology Challenges
• Most J2EE application needs to access one (or
more) relational databases.
• Your persistence strategy not only can determine
an application's performance, but can have a huge
influence on the effort required to develop and
maintain the application—and unless you make the
right design decisions up front.
• It may be hard to revisit this part of the design
after the application is finished.
• Managing portability.
• Paradigm Mismatch between Object Modeling and
Relational Modeling (Identity, Inheritance,
Associations)
December 7, 2021 3
Persistence Technology Choices
• Etc.
December 7, 2021 4
SQL Based Approach
• Write native SQL to store and retrieve objects from the database
• Possibly use to stored procedures
• Use rows and result sets directly.
• Use DAO design pattern to hide complex JDBC code
• Pros:
− No Need for any ORM tool
− Simple JDBC experience with an abstraction framework that doesn't
hide SQL
− Theoretically it should prove more efficient
• Cons:
− Writing and maintain all the SQL is a lot of work(like managing
connection,statements,transaction,security etc)
− Can be a great deal of efforts to add new fields(if it evolves in
future)
− Hard to avoid duplication
− Lots and lots of code in whole application(example ,if data has to be
normalized into three tables,three JDBC insert calls needs to be
made)
− Huge Time commitment in maintenance and testing.
•
December 7, 2021 5
Why Not Entity Bean < V3
Disadvantages with Entity Bean:
• No inheritance Support
December 7, 2021 6
The Goal, more practical
December 7, 2021 7
Hibernate Agenda
December 7, 2021 8
What is ORM?
• Object / Relational Mapping
• 4 Pieces
− API to perform basic CRUD
− API specifying queries
− A facility for specifying mapping meta-data
− To perform Dirty Checking, Lazy association fetching
and other optimization functions.
December 7, 2021 9
Object Relational Mapping (ORM)
December 7, 2021 10
Why Use ORM
• Better system architecture:
− Easier to reuse the code
− Easier to Maintain
− Separate business and persistence logic,so that change in one does not
influence the other
− Migrating application to different database is very easy
December 7, 2021 11
Hibernate Agenda
December 7, 2021 12
Hibernate OR Mapping
• Hibernate is a solution for object relational mapping and a persistence
management solution or persistent layer.
• The mapping files may be leveraged to configure complex relationships,
such as inheritance, one-to-many, many-to-many, etc.
• By using Hibernate, the need for a container such as an EJB container
that adds more overhead than necessary can be avoided
• OpenSource
• Mature
• Popular
• Code can tested and run outside of any containers
• Classes may be reused in non-persistent context
• Minimize database trips with smart fetching strategies
• Works standalone or with most app servers, databases, caching tools,
and other Open Source components
• Long transactions and optimistic locking
• Runtime byte code and SQL generation
December 7, 2021 13
Hibernate OR Mapping
• Build persistent objects following common Java idioms:
• - Association
• - Inheritance
• - Polymorphism
• - Composition
• - Collations API for “many” relation ships
• Performance:
• - High performance Object caching
• - Supports 2 level of caching
− Lazy Collection
− Outer-Join
− Proxy
December 7, 2021 15
Hibernate Architecture (lite)
- In the "lite" architecture the application provide its own JDBC
connections and manages its own transactions.
- This approach uses a minimal subset of Hibernate's APIs
December 7, 2021 16
Hibernate Architecture (Full Cream)
The "full cream" architecture abstracts the application away from
the underlying JDBC/JTA APIs and lets Hibernate take care of the
details.
December 7, 2021 17
Hibernate Interfaces
• Core Interfaces:
• Session Interfaces
− Primary interface
− Light weight and inexpensive to create and destroy
− Hibernate sessions are not threadsafe and should by design be used by only one thread at
a time.
− It’s a persistence Manager since its used for storing and retrieving objects.
• SessionFactory Interfaces
− a single SessionFactory for the whole application
− caches generated SQL statements and other mapping metadata that Hibernate uses at
runtime.
− holds cached data that has been read in one unit of work and may be reused in a future
unit of work (second level cache)
December 7, 2021 19
Hibernate Agenda
December 7, 2021 20
Configurations
• Basic Configurations
• Hibernate configuration file (hibernate.cfg.xml)
• JDBC Connections
• Creating Mapping definitions
• POJO
• Building SessionFactory
• Persisting Objects
• Retrieving Objects
• The session Cache
• Advanced Configuraion
• Connection Pool
• Transactions
• Cache Provider
December 7, 2021 21
A domain Model of an event
December 7, 2021 22
JDBC Configuration in a Non Managed
environment
December 7, 2021 23
JDBC Configuration in a Non Managed
environment
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">uid</property>
<property name="connection.password">pwd</property>
<property name="connection.url">jdbc:mysql://localhost/db</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/manning/hq/ch03/Event.hbm.xml"/>
<mapping resource="com/manning/hq/ch03/Location.hbm.xml"/>
<mapping resource="com/manning/hq/ch03/Speaker.hbm.xml"/>
<mapping resource="com/manning/hq/ch03/Attendee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
December 7, 2021 24
JDBC Configuration in a Managed
environment
December 7, 2021 25
JDBC Configuration in a Managed
environment
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration
DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="java:comp/env/hibernate/SessionFactory">
<property name="connection.datasource">jdbc/myDataSource
</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect
</property>
<mapping resource="com/manning/hq/ch03/Event.hbm.xml"/>
<mapping resource="com/manning/hq/ch03/Location.hbm.xml"/>
<mapping resource="com/manning/hq/ch03/Speaker.hbm.xml"/>
<mapping resource="com/manning/hq/ch03/Attendee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
December 7, 2021 26
Creating Mapping definitions
The Event.hbm.xml mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.manning.hq.ch03">
<class name="Event" table="events">
<id name="id" column="uid" type="long" unsavedvalue="null">
<generator class="native"/>
</id>
<property name="name" type="string" length="100"/>
<property name="startDate" column="start_date"type="date"/>
<property name="duration" type="integer"/>
<many-to-one name="location" column="location_id“ class="Location"/>
<set name="speakers">
<key column="event_id"/>
<one-to-many class="Speaker"/>
</set>
<set name="attendees">
<key column="event_id"/>
<one-to-many class="Attendee"/>
</set>
</class>
</hibernate-mapping>
December 7, 2021 27
Creating Mapping definitions
• Proxies
− An object proxy is just a way to avoid retrieving an object
until you need it.
<class name="Location"proxy="com.manning.hq.ch03.Location"...>...
</class>
<class name="Location" lazy="true"...>...</class>
Example:
Session session = factory.openSession();
Event ev = (Event) session.load(Event.class, myEventId);
Location loc = ev.getLocation();
String name = loc.getName();
session.close();
December 7, 2021 28
Creating Mapping definitions
Collections:
The set definitions declares that the Event class has a property
named speakers, and that it’s a Set containing instances of
the Speaker class.
December 7, 2021 29
Creating Mapping definitions
Cascades:
− all—All operations are passed to child entities: save, update, and delete.
− save-update—Save and update (INSERT and UPDATE, respectively) are
passed to child entities.
− delete—Deletion operations are passed to child entities.
− delete-orphan—All operations are passed to child entities, and objects no
longer associated with the parent object are deleted.
Example
− <set name="speakers" cascade="delete">
− <key column="event_id"/>
− <one-to-many class="Speaker"/>
− </set>
December 7, 2021 30
Creating Mapping definitions
Fetching associated objects:
The fetch attribute allows you to specify which method to use:
December 7, 2021 31
POJO Basics
• Implements the entities of the busniess problem.
package com.manning.hq.ch04;
import java.io.Serializable;
import java.util.Date;
import com.manning.hq.ch04.Location;
public class Event implements Serializable {
private Long id;
private int duration;
private String name;
private Date startDate;
private Location location;
public Event() { }
public Event(String name) {
this.name = name;
}
public Long getId() { return id; }
public void setId(Long id) {
this.id = id;
}
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
public Date getStartDate() { return startDate; }
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public int getDuration() { return duration; }
public void setDuration(int duration) {
this.duration = duration;
}
public Location getLocation() { return location; }
public void setLocation(Location location) {
this.location = location;
}
}
December 7, 2021 32
Main rules to follow
• Declare accessors and mutators for
persistent fields
• Implement a no-argument constructor
• Provide an identifier property (optional)
• Prefer non-final classes (optional)
• Can have Business Methods
December 7, 2021 33
Building SessionFactory
It is used to load all the mapping files and create sessionfactory
for the mapping files.The different ways
• Configuring sessionfactory:
Configuration cfg = new Configuration();
SessionFactory factory = fg.configure().buildSessionFactory();(loads from
hibernate.cfg.xml file)
Configuring Session:
Session session = factory.openSession();
It’s the primary interface which lets to persist objects,query the objetcs and
make the persistent objects transient.
December 7, 2021 34
Persisting Objects
• Save
• Update
• SaveOrUpdate
Configuration cfg = new Configuration();
SessionFactory factory = cfg.buildSessionFactory();
Event event = new Event();
// populate the Event instance
Session session = factory.openSession();
session.saveOrUpdate(event);
session.flush();
session.close();
December 7, 2021 35
Retrieving Objects
Retrieving objects by identifier
Use the cache when retrieving an object, avoiding a database hit if the object
is already cached
− User user = (User) session.get(User.class, userID);
Retrieving an Object using HQL
Object-oriented dialect of the familiar relational query language SQL
Query q = session.createQuery("from User u where u.firstname = :fname");
q.setString("fname", "Max");
List result = q.list();
Query by Criteria
The (QBC) API lets you build a query by manipulating criteria objects at
runtime.
Criteria criteria = session.createCriteria(User.class);
criteria.add( Expression.like("firstname", "Max") );
List result = criteria.list();
December 7, 2021 36
Retrieving Objects Contd…
• Query by example
Application supplies an instance of the queried
class with certain property values set (to nondefault
values).
User exampleUser = new User();
exampleUser.setFirstname("Max");
Criteria criteria = session.createCriteria(User.class);
criteria.add( Example.create(exampleUser) );
List result = criteria.list();
Direct SQL
session.createSQLQuery(
"select {c.*} from CATEGORY {c} where NAME like 'Laptop%'",
"c",
Category.class);
December 7, 2021 37
Caching Objects
• Caching the objects improves the performance
Session session = factory.openSession();
Event e = (Event) session.load(Event.class, myEventId);
e.setName("New Event Name");
session.saveOrUpdate(e);
// later, with the same Session instance
Event e = (Event) session.load(Event.class, myEventId);
e.setDuration(180);
session.saveOrUpdate(e);
session.flush();
Evicting the first instance
Session session = factory.openSession();
Event firstEvent = (Event) session.load(Event.class, myEventId);
// ... perform some operation on firstEvent
if (session.contains(firstEvent)) {
session.evict(firstEvent);
}
Event secondEvent = new Event();
secondEvent.setId(myEventId);
session.save(secondEvent);
December 7, 2021 38
Advanced Features
• Connection Pooling
Application servers often provide their own connection pools using a JNDI DataSource,
which Hibernate can take advantage of when configured to use a DataSource.
December 7, 2021 39
Advanced Features
• Transactions
− Hibernate has its own transaction code
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Event event = new Event();
// ... populate the Event instance
session.saveOrUpdate(event);
tx.commit();
To use JTA Transactions we need the following entry in
hibernate.cfg.xml
<property name="transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</property>
<property name="jta.UserTransaction">
java:comp/UserTransaction
</property>
December 7, 2021 40
Advanced Features-Caching
• A cache keeps a representation of current database state close to
the application,either in memory or on disk of the application
server machine.
• The cache is a local copy of the data. The cache sits between
your application and the database.
• The cache may be used to avoid a database hit whenever
• ■ The application performs a lookup by
identifier (primary key)
• ■ The persistence layer resolves an association lazily
• First Level Cache Scope
− Session scope.Transaction scope .
• Second Level Cache Scope
− Scoped to Process or cluster
December 7, 2021 41
Hibernate: Dual Layer Cache
• Session level cache
1. * A session-level cache resolves repeated requests for the
same instance in a particular session.
2. * transaction-level cache of persistent data
3. * Whenever you pass an object to save(), update() or
saveOrUpdate() and whenever you retrieve an object using
load(), find(), iterate(), or filter(), that object is added to
the internal cache of the Session.
4. Evict() method can be used to remove an object from
session.
5. Optional second-level cache
6. * cluster or JVM-level (SessionFactory-level) cache
7. * Hibernate features an extremely granular (class or
collection role) second-level cache.
8. * The actual cache implementation is completely pluggable
and supports clustered cache solutions like Tangosol
Coherence, SwarmCache, JBoss TreeCache, as well as
process-level cache implementations such as EHCache and
OSCache.
9. The second-level cache is appropriate for immutable data .
December 7, 2021 42
Caching in practice
Choose a concurrency strategies
− Defines the transaction isolation Status details
• Transactionl
• Read-write
• Nonstrict-read-write
• Read-only
<class
name="Category"
table="CATEGORY">
<cache usage="read-write"/>
<id ....
<set name="items" lazy="true">
<cache usage="read-write"/>
<key ....
</set>
</class>
Choose a cache region
Represents physical,actual cache implementation
org.hibernate.auction.Category, or org.hibernate.auction.Category.Items
If you have data that is updated more often than it’s read, don’t enable the
second-level cache, even if all other conditions for caching are true!
December 7, 2021 43
Caching in practice contd…
Define cache configuration in
provider.xml example ehcache.xml
<cache name="org.hibernate.auction.model.Bid"
maxElementsInMemory="5000"
eternal="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="100000"
overflowToDisk="false"
/>
− timeToIdleSeconds-defines the expiry time in seconds since
an element was last accessed in the cache
− timeToLiveSeconds-defines the maximum expiry time in
seconds since the element was added to the cache
December 7, 2021 44