You are on page 1of 23

Workshop on Hibernate

Authors: Rely-On Solutions

People : Process : Technology : Tools

©©Rely-On
Rely-On 2005;
2005; For further
For further information
information on Rely-On,
on Rely-On, please
please visit visit www.rely-ongroup.com
www.rely-ongroup.com
Hibernate Workshop

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Agenda
• Caching
•Hibernate Caching Archotecture
•Hibernate API to control Cache
•Working with EHCache
•Connection Pooling
•C3PO Connection Pool
•Hibernate Performance
•Hibernate Best Practices
•Whats new with Hibernate 3.0

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Caching
• representation of current database state close to the
application, either in memory or on disk of the application
server machine.
• sits between your application and the database.
• 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
Types of Cache
• Transaction scope=> Attached to the current unit of work, which may be an
actual database transaction or an application transaction. Every unit of work has
its own cache.
•Process scope=> Shared among many (possibly concurrent) units of work or
transactions.
•Cluster scope=> Shared among multiple processes on the same machine or
among multiple machines in a cluster. It requires some kind of remote process
communication to maintain consistency.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Hibernate Cache Architecture

Mandatory

Pluggable

Second Level Cache


•might be scoped to the process or cluster. All Session shares this.
•Cache of state and not of persistence instances
•Cache concurrency strategy defines the transaction isolation details
•Cache provider provides the actual physical implementation
•Optional
•Can be configured per-class or per-association basis

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Cache Policy
• Whether the second-level cache is enabled
• The Hibernate concurrency strategy
• The cache expiration policies (such as timeout, LRU, memory-
sensitive)
• The physical format of the cache (memory, indexed files, cluster-
replicated)
• useful only for read mostly classes.

Cache Setup. 2 step process


•Decide on concurrency strategy- responsible for storing items of data in the
cache and retrieving them from the cache.
• Decide on cache provider

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Cache Concurrency Strategy
• transactional
– in a managed environment only.
– guarantees full transactional isolation up to repeatable read
– strategy for read-mostly data where it’s critical to prevent stale data

• read-write
– Maintains read committed isolation, using a timestamping mechanism.
– only in non-clustered environments.
– use this strategy for read-mostly data

• nonstrict-read-write
– Makes no guarantee of consistency between the cache and the database.
– configure a sufficiently short expiry timeout.
– Use this strategy if data rarely changes (many hours, days or even a week) and a
small likelihood of stale data isn’t of critical concern.

• read-only
– A concurrency strategy suitable for data which never changes.
– Use it for reference data only.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Cache provider

Features Supported

write an adaptor for other products by implementing


net.sf.hibernate.cache.CacheProvider.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Using Hibernate 2nd Level Cache

For POJOs

For collections

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Setting up cache

ehcache.xml

<cache name="org.hibernate.auction.model.Category"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"/>

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Connection Pooling using C3P0
• Put c3p0 jar in WEB-INF/lib
• Put c3p0.properties in WEB-INF/classes
– Modify properties as required
• Modify hibernate.cfg.xml to use C3P0

hibernate.cfg.xml
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property>
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">100</property>

Rest of the properties can be set in c3p0.properties file.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


C3P0 Properties
• initialPoolSize Initial Pool size. C3P0 default: 3

• minPoolSize Minimum pool size. Must be set in hibernate.cfg.xml (or hibernate.properties),


Hibernate default: 1

• maxPoolSize Maximum pool size. Must be set in hibernate.cfg.xml (or hibernate.properties),


Hibernate default: 100

• idleTestPeriod c3p0 will test all idle, pooled but unchecked-out connections. Must be set in
hibernate.cfg.xml (or hibernate.properties), Hibernate default: 0

• timeout Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 0


• The seconds a Connection can remain pooled but unused before being discarded. Zero means idle
connections never expire.

• maxStatements Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 0


The size of c3p0's PreparedStatement cache. Zero means statement caching is turned off.

• propertyCycle Must be set in c3p0.properties, C3P0 default: 300 Maximum time in seconds before
user configuration constraints are enforced. c3p0 enforces configuration constraints continually,
and ignores this parameter. It is included for JDBC3 completeness.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


C3P0 Properties (contd.)
• acquireIncrement Must be set in hibernate.cfg.xml (or hibernate.properties), Hibernate default: 1
Determines how many connections at a time c3p0 will try to acquire when the pool is exhausted.

• testConnectionOnCheckout Must be set in c3p0.properties, C3P0 default: false Don't use it, this
feature is very expensive. If set to true, an operation will be performed at every connection checkout
to verify that the connection is valid. A better choice is to verify connections periodically using
c3p0.idleConnectionTestPeriod.

• autoCommitOnClose Must be set in c3p0.properties, C3P0 default: false The JDBC spec is
unfortunately silent on what should happen to unresolved, pending transactions on Connection
close. C3P0's default policy is to rollback any uncommitted, pending work.

• forceIgnoreUnresolvedTransactions Must be set in c3p0.properties, C3P0 default: false. Setting


this to true may lead to subtle and bizarre bugs.

• numHelperThreads Must be set in c3p0.properties, C3P0 default: 3. c3p0 is very asynchronous.


Slow JDBC operations are generally performed by helper threads that don't hold contended locks.
Spreading these operations over multiple threads can significantly improve performance by allowing
multiple operations to be performed simultaneously.

• factoryClassLocation Must be set in c3p0.properties, C3P0 default: null DataSources that will be
bound by JNDI and use that API's Referenceable interface to store themselves may specify a URL
from which the class capable of dereferencing a them may be loaded. If (as is usually the case) the
c3p0 libraries will be locally available to the JNDI service, leave this set to null.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Hibernate Performance
• Collection Performance
– 3 Basic kinds of collections
 Collection of values
 One to many associations
 Many to Many associations
– Structure of primary key
 Indexed collections
 Sets
 Bags
– All indexed collection (list,map,arrays) has primary key (<key>
& <index>)
– Updates and deletes are extremely efficient.
– Sets have primary key (<key>), but as efficient when
composite keys and binary data
– Bags have duplicate columns, and no indexes. Updates and
delete is not as fast as maps, sets, list and arrays.
– Bags and lists are more efficient when inverse=“true” is
enabled.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Hibernate Performance
• Using batch fetching
– an optimization for the lazy loading strategy
 <class name="Person" lazy="true" batch-size="10">...</class>
 For loading 25 persons, it will retrieve 10+10+5 in 3 selects instead of 25
selects.
– Same in retrieving collection
 <class name="Person"> <set name="cats" lazy="true" batch-size="3"> ... </set> </class>
 Instead of 10 selects for it will execute 4 selects for 3+3+3+1 Cat.
• The Second Level Cache
– Cache on per class or per collection basis
 <cache usage="transactional|read-write|nonstrict-read-write|read-only"/>

– Strategy
 Read/write
– needs to update data
– never be used if serializable transaction isolation level is required
 Nonstrict read/write
– occasionally needs to update data
– strict transaction isolation is not required

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Hibernate Performance
– Transactional
 only be used in a JTA environment and you must specify
hibernate.transaction.manager_lookup_class
• The Query Cache
– only useful for queries that are run frequently with the same
parameters
– Enable it by hibernate.cache.use_query_cache=true.
– Most queries do not benefit from caching, so by default queries
are not cached

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Hibernate Best Practices
• Write fine-grained classes and map them using <component>.
– encourages code reuse and simplifies refactoring.
• Declare identifier properties on persistent classes.
– identifiers be 'synthetic' (generated, with no business meaning) and
– of a non-primitive type. For maximum flexibility, use java.lang.Long or
java.lang.String.
• Place each class mapping in its own file.
– good sense in a team environment.
• Load mappings as resources.
– Deploy the mappings along with the classes they map.
• Consider externalizing query strings.
– will make the application more portable.
• Use bind variables.
– As in JDBC, always replace non-constant values by "?".
– Never use string manipulation to bind a non-constant value in a query!
– consider using named parameters in queries.
• Don't manage your own JDBC connections.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Hibernate Best Practices
• Use hand-coded JDBC in bottlenecks.
– wait until you know something is a bottleneck.
• Understand Session flushing.
– Performance will be affected if this process occurs too often.
– minimize unnecessary flushing by disabling automatic flushing
• In a three tiered architecture, consider using saveOrUpdate().
– When using a servlet / session bean architecture
Session.saveOrUpdate() to update the persistent state of an object.
• In a two tiered architecture, consider using session disconnection.
– Database Transactions have to be as short as possible for best
scalability.
– In application Transaction either use Detached Objects or,
– in two tiered architectures, simply disconnect the Hibernate Session
from the JDBC connection and reconnect it for each subsequent request.
– Never use a single Session for more than one Application Transaction
usecase, otherwise, you will run into stale data.
• Don't treat exceptions as recoverable.
– When an exception occurs, roll back the Transaction and close the
Session. If you don't, Hibernate can't guarantee that in-memory state
accurately represents persistent state.
– do not use Session.load() to determine if an instance with the given
identifier exists on the database; use find() instead.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Hibernate Best Practices
• Prefer lazy fetching for associations.
– Use eager (outer-join) fetching sparingly.
– lazy collections for most associations to classes
– When an outer-join fetch is appropriate to a particular use case, use a
query with a left join fetch.
• Consider abstracting your business logic from Hibernate.
– Hide (Hibernate) data-access code behind an interface. Combine the
DAO and Thread Local Session patterns.
• Implement equals() and hashCode() using a unique business key.
– never ever use the database identifier!
– use a unique business key, that is, compare a unique combination of
class properties
• Don't use exotic association mappings.
– many-to-many associations are rare.
– use two one-to-many associations to an intermediate link class.
• Consider using a custom type.
– consider implementing net.sf.hibernate.UserType.

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


What’s new in Hibernate3?
• introduced new event-driven design
• added <dynamic-class>
• Added statistics per SessionFactory
• automatic dialect detection if no dialect is configured
• Added support for JDBC escape sequences in createSQLQuery
• Added <sql-insert>, <sql-update> and <sql-delete> support
• Added catalog element, to enable table names like catalog.schema.table
• added lazy="true" to property mappings
• added subselect mappings
• added extra attributes to named query definition
• added <join/> for multitable mappings
• added <union-subclass/> for table-per-concrete-class strategy
• added Filter API and mappings, for temporal, regional and permissioned data
• added JDBCException.getSQL() and made various improvements to exception flow
• added sequential-select, optional and inverse attributes to <join/>
• added MySQLMyISAMDialect and MySQLInnoDBDialect
• added dialect for Derby
• added precision and scale mapping attributes, for numeric types in DDL
• added EJB3 compliant create() and merge() operations
• added default-lazy to <hibernate-mapping>, which defaults to true
• added typed JDBC exceptions
• added full support for implicit polymorphism in Criteria queries
• added CacheMode
• added EnhancedUserType, UserCollectionType, UserVersionType
• added support for bulk update/delete against discriminator-based inheritence hierarchies
• added HQL projection feature, return Lists instead of arrays for projection

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Summary

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Q&A

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com


Feedback

© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com