Saturday, April 17, 2010

Introduction to Java Hibernate

Introduction to Java Hibernate

Objectives of this document is to give readers an understanding of the following issues

Object Relational Impedance Mismatch
Benefits of Hibernate as ORM Framework
Architecture of Hibernate Framework
Persistence Life Cycle

Object Relational Impedance Mismatch:
There are a number of differences in the Relational Model (used in database) and Object Oriented Model (used by programming languages). These differences are referred to as Impedance Mismatch. Some areas of Impedance Mismatch are as follows

Identity

In OOP “Identical” and “Equal” are different notions. Two objects are equal if they refer to the same memory location i.e. equality in OOP does not take into consideration the contents of the object but only the reference. However the “equals” method can be overridden to check the contents rather than the reference. In relational database, the equality is based upon the primary key of entity

Inheritance
In RDBMS, inheritance is not supported.
Associations
In RDBMS many-to-many relationships are not directly supported and are modeled via bridge tables. Where as in OOP such relationships can be easily modeled by having collections containing related objects at each end of the relationship. For example a student class may consist of collection having related course and course class may consist of a collection containing students related to that particular course.
Due to above reasons a number of ORM frameworks are available. However among all those, hibernate has become very popular because of the following reasons

Benefits of Hibernate


Simple and Flexible

Single configuration file and one mapping for each application object to be persisted
No need to inherit any classes

Completeness
Complete support for OOP
Has special query language similar to SQL

Performance
Issues statements only when state of object changes
Collections are loaded when they are needed
Properties are populated when needed
Users can disable which associated object will not be loaded
Supports caching

Architecture of Hibernate
Makes use of existing Java APIs including
JDBC for data access
JTA and JNDI enable integrity with JEE
Interfaces provided by Hibernate belong to four categories
Called by applications to perform CRUD and Queries e.g. Session, Transaction and Query
Called by applications to Configure hibernate, e.g. Configuration
Used by applications to react to events occurring inside hibernate. e.g. Interceptor, Lifecycle and Validatable.
Enable extending Hibernate’s powerful mapping functions e.g UserType, CompositeUserType and IdentifierGenerator. (These are implemented by application infrastructure code.)

Following is a description of some important interfaces
Session Interface
It is the Primary interface used by applications
Session is Lightweight and inexpensive to create and destroy
It must be noted that it is not thread safe
It can be considered as cache or collection of loaded objects related to a single unit of work
Also called persistence manager as it performs loading and saving

SessionFactory

Instances of SessionFactory are Heavy weight
And thread safe as they are Intended to be shared among multiple threads
Each object of sessionFactory will represent a single database
Caches generated SQL, mapping metadata for runtime and data (only in-case of second-level cache)

Configuration interface
The Configuration object is used to configure and bootstrap Hibernate
Creates the SessionFactory

Transaction

Optional Interface
Abstracts application code from underlying transaction implementation

Query and Criteria Interface
Query is lightweight and can’t be used out of session
can be used to
Bind parameters
Limit the number of result
Execute Query

Criteria is similar to queries
Create and execute object oriented criteria queries

Callback Interfaces
Allows applications to receive notifications
LifeCycle and Validate needs to be implemented by persisted classes(Not preferred)
Interceptor needs not be implemented by persistent classes.

Type interface
Hibernate supports rich type system
Nevertheless, custom types can be created using
UserType
CompositeUserType

Extension Interfaces
Customized Implementation of certain interfaces possible
Enables plugging in code into hibernate framework
Extension Points and Corresponding Interfaces
Primary key generation (IdentifierGenerator interface)
SQL dialect support (Dialect abstract class)
Caching strategies (Cache and CacheProvider interfaces)
DBC connection management (ConnectionProvider interface)
Transaction management (TransactionFactory, Transaction, and TransactionManagerLookup interfaces)
ORM strategies (ClassPersister interface hierarchy)
Property access strategies (PropertyAccessor interface)
Proxy creation (ProxyFactory interface)

Persistence Life Cycle
Hibernate persistence is Transaction-Scoped
In the context a row will be represented by a single instance
When same row is retrieved twice reference to single instance will be returned
Defines three states for an object
Transient
Persistent
Detached

Transient
Objects created with new operator
Not associated with any database row
Their state garbage collected when dereferenced
Considered non-transactional by hibernate
Can be made persistent
By calling save method
Creation of reference from an already persistent instance

Persistent
Any instance with a database identity
Always associated with persistence manager i.e. Session
Are Transactional
i.e. Their state is synchronized with database at the end of transaction
SQL queries are used for this purpose
Can be retrieved from database by
Executing Query
Identifier Lookup
Navigating object graph starting from persistent instance
Instance is called new if Identity allotted but not stored in database yet

Detached
Objects no longer associated with persistence manager
This happens when the session is closed
Their state is no longer guaranteed to be synchronized with Database
A detached instance can be re-associated with another Persistence manager

Above were some of the basics of Hibernate. This post will be appended with more material related to hibernate basics.

No comments:

Post a Comment