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

July 28, 2010

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)
July 28, 2010 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.

July 28, 2010

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 hide SQL í Theoretically it should prove more efficient

doesn't

‡

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.

‡

July 28, 2010

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

July 28, 2010

6

The Goal, more practical

‡ Take the advantage of those things that Relational Database do well ‡ Without leaving the language of objects /classes

July 28, 2010

7

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

July 28, 2010

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

í í í í
July 28, 2010

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

Object Relational Mapping (ORM)

July 28, 2010

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

July 28, 2010

11

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

July 28, 2010

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
July 28, 2010 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
July 28, 2010 14

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

July 28, 2010

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

July 28, 2010

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.

July 28, 2010

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.
July 28, 2010 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

July 28, 2010

19

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

July 28, 2010

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
21

July 28, 2010

A domain Model of an event

July 28, 2010

22

JDBC Configuration in a Non Managed environment

July 28, 2010

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>

July 28, 2010

24

JDBC Configuration in a Managed environment

July 28, 2010

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>

July 28, 2010

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>
July 28, 2010 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();
July 28, 2010 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; } ... }
July 28, 2010 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>

July 28, 2010

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)

July 28, 2010

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; }

}

July 28, 2010

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

July 28, 2010

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.
July 28, 2010 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();

July 28, 2010

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();

July 28, 2010

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);
July 28, 2010 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);
July 28, 2010 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>

July 28, 2010

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>
July 28, 2010 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
July 28, 2010 41

Hibernate: Dual Layer Cache
‡ 1. 2. 3.

4. 5. 6. 7. 8.

9.

Session level cache * A session-level cache resolves repeated requests for the same instance in a particular session. * transaction-level cache of persistent data * 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. Evict() method can be used to remove an object from session. Optional second-level cache * cluster or JVM-level (SessionFactory-level) cache * Hibernate features an extremely granular (class or collection role) second-level cache. * 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. 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

‡

July 28, 2010

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!
July 28, 2010 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
July 28, 2010 44

Sign up to vote on this title
UsefulNot useful