0% found this document useful (0 votes)
117 views44 pages

Hibernate - ORM Technology For Java: Shantha Lakshmi (JCOE Team) 16/07/2008

Uploaded by

Akash Chaudhary
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views44 pages

Hibernate - ORM Technology For Java: Shantha Lakshmi (JCOE Team) 16/07/2008

Uploaded by

Akash Chaudhary
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Hibernate – ORM

Technology for Java


Shantha Lakshmi (JCOE Team)
16/07/2008

© 2004 Hewlett-Packard Development Company, L.P.


The information contained herein is subject to change without notice
Hibernate Agenda

1. Introduction to Persistence Technology


2. Understanding O/R Mapping
3. Introduction to Hibernate
4. Hibernate Architecture
5. Hibernate configuration
6. Associations
7. Collections
8. HQL queries
9. Hibernate Annotations

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

Relational database access from JSE and JEE


environments may be achieved in one of many ways

• “Raw” JDBC Data Access Objects (DAOs) may make SQL


calls directly to a database

• Spring Persistence Helpers, such as the JDBC Template


class may be leveraged

• Hibernate may be leveraged

• iBatis may be leveraged

• EJB 3.0 entity beans may be leveraged

• 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:

• Usability Problems: Too many classes required, Exclusive


use of checked exceptions, proprietary descriptors

• Since CMP beans one-to-one mapping to the table, its


course- grained. Hence its forces first normal form.

• Application servers dependant / not portable in practice /


Vendor Specific engines

• So unit testing is difficult in Test Driven Development


model

• Not Serializable, need additional Data Transfer Objects/


Value Objects

• No inheritance Support

• EJB query languages are static

December 7, 2021 6
The Goal, more practical

• Take the advantage of those things


that Relational Database do well

• Without leaving the language of


objects /classes

December 7, 2021 7
Hibernate Agenda

Introduction to Persistence Technology


Understanding O/R Mapping
Introduction to Hibernate
Hibernate Architecture
Hibernate configuration
Associations
Collections
HQL queries
Hibernate Annotations

December 7, 2021 8
What is ORM?
• Object / Relational Mapping

• Automated persistence of objects in Java application to


the tables in RDB using Meta-Data

• Meta-Data describes the mapping between the objects


and the database

• Copying of tables to objects and vice versa is called


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

• Reduce time for standard DB actions:


− Can radically reduce the amount of code need to write
− ORM eliminates the requirement to write SQL to load and persist object
state

• Advanced features difficult to develop


yourself:
− automatic change detection
− eliminating an error-prone task from the development life-cycle
Caching Solutions.
- Transactions

December 7, 2021 11
Hibernate Agenda

Introduction to Persistence Technology


Understanding O/R Mapping
Introduction to Hibernate
Hibernate Architecture
Hibernate configuration
Associations
Collections
HQL queries
Hibernate Annotations

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

• Sophisticated query facilities:


• - Hibernate query Language ( HQL)
• - Criteria API and query by criteria
• - Query by Example
December 7, 2021 14
Hibernate Agenda

Introduction to Persistence Technology


Understanding O/R Mapping
Introduction to Hibernate
Hibernate Architecture
Hibernate configuration
Associations
Collections
HQL queries
Hibernate Annotations

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)

• Configuration Interfaces: The Configuration object is used to configure and bootstrap


Hibernate.
• Transaction Interfaces: to managing transactions in given infrastructure, supports JDBC, JTA
and CORBA transaction to control transaction boundaries. [portability]
• Query and Criteria Interfaces
− The Query interface allows you to perform queries against the database and control how
the query is executed. Queries are written in HQL or in the native SQL dialect of your
database.
− The Criteria interface is very similar; it allows you to create and execute object oriented
criteria queries.
December 7, 2021 18
Hibernate Interfaces contd…
• Callback Interfaces:
− Callback interfaces allow the application to receive a
notification when something interesting happens to an object
—for example, when an object is loaded, saved,or deleted.
Interceptor, Lifecycle, and Validatable.
• Types:
− Fundamental and very powerful element
− Maps Java type to a database column type
− Provides usertype and CompositeUSerType to allow to add
user defined custom types

December 7, 2021 19
Hibernate Agenda

Introduction to Persistence Technology


Understanding O/R Mapping
Introduction to Hibernate
Hibernate Architecture
Hibernate configuration
Associations
Collections
HQL queries
Hibernate Annotations

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.

public class Event {


private Set speakers;
...
public void setSpeakers(Set speakers) {
This.speakers = speakers;
}
public Set getSpeakers() {
return this.speakers;
}
...
}

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:

<many-to-one name="location" class="Location"


fetch="join"/>
(outer join to fetch the associated instance when an Event
class is loaded)

<many-to-one name="location" class="Location"


fetch="select"/>
(When its required to fetch the objects separately)

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)

Configuration cfg = new Configuration();


cfg.addFile("com/manning/hq/ch03/Event.hbm.xml");

Configuration cfg = new Configuration();


cfg.addClass(com.manning.hq.ch03.Event.class);

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.

For a standalone application,hibernate supports 3 connection pooling servcies


C3P0, Apache’s DBCP library, and Proxool.
<property name="connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
Once the provider class is set, the specific properties for the pooling
service can also be configured from the hibernate.cfg.xml file:
<property name="c3p0.minPoolSize">
5
</property>
...
<property name="c3p0.timeout">
1000
</property>

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 .

• Optional query cache


* Query result sets may be selectively cached
* useful for queries that are run frequently with the same
parameters
* By default queries are not cached. To enable caching, call
Query.setCacheable(true).
* Both the second-level and query cache may be clustered

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

Select a local cache provider


hibernate.cache.provider_class=net.sf.ehcache.hibernate.Provider

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

You might also like