Hibernate, created by Gavin King, known as the best and dominated object/relational persistence (ORM) tool for Java developers (Now is support .NET). It provides many elegant and innovative ways to simplifies the relational database handling task in Java.
Hibernate is great at a lot of things, but its something that needs to be used appropriately. In this tutorials, it providing many step by step examples and explanations on using Hibernate3
2. Introduction
Object – Relational Mapper(O-R mapper)
Developed by Gavin King in 2001
Alternative to EJB CMP 2.0
Now part of JBoss
Current version – 4.2.2
3. O-R Mapper
Persists objects into database
Maps java object to table and properties to column
No need to write JDBC code
Provides api for performing CRUD operations on objects
Transaction Management
E.g. Hibernate, JPA, TopLink, IBatis
5. Features
POJO entities
Provides API for performing CRUD operations on objects
Query API
Transaction Management
Rich Hibernate Query Language
Concurrency control
Caching
6. Entity
POJO class that model the domain object
Represents table
Contains properties and getter & setters
Persistent
Annotated with @Entity
Optionally can define @Table and @Column
8. Identifier
The property that represents pk
The property is annotated with @ID
Id generation strategy – Auto, Identity, Sequence, Table
Auto – Uses any of Identity, Sequence, Table generator
Sequence – Uses sequence
Identity – Represents identity column of mysql, sqlserver db
Table – Uses table to store pks
9. SessionFactory, Session & Transaction
Factory class for creating session
There should be only 1 instance of SessionFactory
Session provides api for CRUD
Application uses session for persistence
One session/request
Transaction is started using session
Transaction provides commit and rollback
11. Configuration
Configurations are specified in hibernate.cfg.xml
It defines –
db connection parameters
datasource
transaction facory class
entities/mapping xml
20. Lazy Loading
Load the data only when it is required
In relationships, when a particular entity is queried its related entities
may not be required
Lazy loading ensures that entire object graph is not created in memory
saving memory
Lazy loading returns proxy object for related entity
When ‘get’ is called on proxy, query is fired and all the data gets
loaded……..Session should be active
Employee Proxy
Department
21. Fetch Strategies
Eager – Load all data at once
Lazy – Lazy loading
@ManyToOne, @OneToMany @ManyToMany has fetch
attribute to specify fetching strategy
22. Open Session In View Pattern
Lazy Loading requires session to be active during view
rendering
It is implemented using a Filter – It begins and ends
transaction and session
Spring contains OpenSessionInViewFilter
23. Hibernate Query language(HQL)
Similar to sql but uses class and property instead of table &
column
Query class provides querying functionality
HQL supports =,!=,<,>,In, Like, Between, And, Or
operators
Supports group by, order by
26. Scalar/projection Queries
Returns scalar values rather than entities
Specify properties to be returned after ‘select’ in query
Returns list of objects or object arrays
28. Named Query
It is a query defined at entity level with name and query
string
Global scope
Defined using @NamedQuery and @NamedQueries
Query instance is obtained using Session
29. Criteria API
Query can be created dynamically using api
Criterion represents one expression in where clause and it
is added to Criteria
Restrictions provide methods to create Criterion
30. Query By Example
Example class is a type of Criterion
Provides simplest way to create where condition based on
the entity object
31. Bulk Update & Delete
For updating/deleting multiple rows, HQL provides
update/delete query
No need to load so many objects and then call
session.update() or session.delete()
33. Caching
1st Level Cache(Session level)
Every session has its own cache
2nd Level Cache
It is application level cache and common to all sessions
Cache provider needs to be configured in hibernate.cfg.xml.
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
E.g. Ehcache, OSCcahe, JBoss Cache, SwarmCache
<cache name="auction.model.Category“ maxElementsInMemory="500“
eternal="true“ timeToIdleSeconds="0"
timeToLiveSeconds="0“ overflowToDisk="false“/>
34. Concurrency Control
Lost update:
When two transactions are executing concurrently, 2nd transaction can overwrite
the changes made by 1st transaction
Optimistic Locking/Versioning:
Add a property annotated by @Version
Supported data type – int, long, Timestamp
Add a version column in table
Whenever entity is updated version is incremented
If db version is not same as entity’s version then exception is thrown during
transaction commit
36. Concurrency Control
Pessimistic Locking:
Session provides lock() method that explicitly locks a row
2nd Transaction can get the entity only when 1st Transaction has
committed. This ensures that 2nd transaction has updated data
and not stale data.
Lock mode also can be passed in get() method
37. Inheritance
Inheritance Strategies -:
Table per class hierarchy(Single_Table)
Single Table for all classes in inheritance hierarchy
Subclasses are distinguished by Discriminator column
@DiscriminatorColumn, @DiscriminatorValue
38. Inheritance
Table per concrete class (Table_Per_Class)
Separate table for every concrete subclass
Every table should contain columns for superclass
properties
Column name of super class properties can be changed
using @Override
39. Inheritance
Table per sub class (Joined)
Separate table for every superclass & subclass
Every table should contain columns only for its own
properties and not inherited properties
Data is retrieved by joining superclass and subclass
tables
40. Filters
Hibernate provides Filter for filtering objects returned by
any query
Define filter using @FilterDef
Apply the filter to entity using @Filter on entity class
Enable filter on session and set filter params
Filter can be applied to @OneToMany relationship fields