Saturday, February 27, 2010

An introduction to Hibernate

                                                                                           -Srinivas Reddi
What is Hibernate?


Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent objects following common Java idioms –including association, inheritance, polymorphism, composition, and the Java collections framework

Why Hibernate?

To make the application developemnt more productive. It saves development time and also mainly it deals with Objects(POJO) . and .xml file which has nothing but mapping between database column and POJO variable. You can easily switch the database from MySql to Oracle.You need not change any of your code... just you need to change a simple dialect in configuration file of hibernate and it works.

Features:

• Released under LGPL (Lesser GNU Public License)
• Supports over 30 dialects (like drivers for different DBs)
• Departs from the JDO approach
• Supports transparent object persistence
• Provides rich query language
• Caching
• JMX support
• Based on Beans and Reflection
• Upside–Low resource contention, small foot print–High performance (in spite of the use of reflection!)

Hibernate Architecture

A (very) high-level view of the Hibernate architecture:





This diagram shows Hibernate using the database and configuration data to provide persistence services (and persistent objects) to the application.

We would like to show a more detailed view of the runtime architecture. Unfortunately, Hibernate is flexible and supports several approaches. We will show the two extremes. The "lite" architecture has the application provide its own JDBC connections and manage its own transactions. This approach uses a minimal subset of Hibernate's APIs:




The "full cream" architecture abstracts the application away from the underlying JDBC/JTA APIs and lets Hibernate take care of the details.





Here are some important definitions of the objects in the diagrams:

SessionFactory (org.hibernate.SessionFactory)

A threadsafe, immutable cache of compiled mappings for a single database. A factoryfor Session and a client of ConnectionProvider, SessionFactory can hold an optional(second-level) cache of data that is reusable between transactions at a process, or cluster level.

Session (org.hibernate.Session)

A single-threaded, short-lived object representing a conversation between the application andthe persistent store. It wraps a JDBC connection and is a factory for Transaction. Sessionholds a mandatory first-level cache of persistent objects that are used when navigating theobject graph or looking up objects by identifier.Persistent objects and collectionsShort-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one Session. Once the Session is closed, they will be detached and free to use in any application layer (for example,directly as data transfer objects to and from presentation).Transient and detached objects and collectionsInstances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not yet persisted, or they may have beeninstantiated by a closed Session.

Transaction (org.hibernate.Transaction)

 A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBAtransaction. A Session might span several Transactions in some cases. However,transaction demarcation, either using the underlying API or Transaction, is never optional.

ConnectionProvider (org.hibernate.connection.ConnectionProvider)

 A factory for, and pool of, JDBC connections. It abstracts the application fromunderlying Datasource or DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

TransactionFactory (org.hibernate.TransactionFactory)

 A factory for Transaction instances. It is not exposed to the application, but it can
be extended and/or implemented by the developer.Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer.Given a "minimal" architecture, the application bypasses the Transaction/TransactionFactory and/or ConnectionProvider APIs to communicate with JTA or JDBC directly.

Some more important terms commonly used:

Instance states in Hibernate

An instance of a persistent class can be in one of three different states. These states are definedin relation to a persistence context. The Hibernate Session object is the persistence context. The three different states are as follows:

transient

The instance is not associated with any persistence context. It has no persistent identity or primary key value.

persistent

The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and can have a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity in relation to the in-memory location of the object.

detached

The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and can have a corresponding row in the database. For detached instances, Hibernate does not guarantee the relationship between persistent identity and Java identity.

SQL Dialects

• A dialect tunes the environment to the specified database.
• Set the hibernate.dialectproperty to the correct org.hibernate.dialect.Dialectsubclass.
•Hibernate will use sensible defaults for some of the properties
•Example
–org.hibernate.dialect.MySQLDialect
–org.hibernate.dialect.SQLServerDialect

O/R Mapping

Object/relational mappings are usually defined in an XML document. The mapping document is designed to be readable and hand-editable. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations and not table declarations.

Sub classes

• Inheritance hierarchy can be easily mapped to tables –Table per class
• The entire hierarchy is maintained in one table
and elements–Table per sub class
• Separate table for each subclass with the common fields in the base class table
element–Table per concrete class
• Separate table for each subclass with all the fields found in each table

Hibernate Query Language- HQL

• Brings the power of SQL
• Fully object-oriented
• Understands notions like inheritance, polymorphism and association
• Written for Objects and not for tables like SQL
• Case-insensitive, except for names of Java classes and properties.

Joins

• Joins supported by HQL
–inner join
–left outer join
--right outer join
–full join

Named Parameters

• Bind values to named parameters or JDBC-style ? parameters.
• Named parameters are identifiers of the form :name in the query string.
• Hibernate numbers parameters from zero.

Named Queries

• Queries can be defined in the mapping document.
• Placed in a CDATA section

Criteria

• Queries can be built dynamically
• An object-oriented API is provided rather than building query strings.
• Hibernate provides an intuitive Criteria query API
–org.hibernate.criterion

Persistent Mechanism

Session

• Session is the central API class of a persistence service
• org.hibernate.Session
• Runtime interface between application and Hibernate
• Make an object persistent by associating it with a session
• Provides methods to make an object persistent, transient or detached

Persisting Objects

• Objects are made persistent using
•save() or persist()
Finding an object

• Hibernate Query Language allows you to issue query
• Matching objects are returned as java.util.List

Deleting objects

• Session’s delete method does this
• You may pass an object or a query string to delete
• The delete may affect an object or its child objects depending on mapping property “cascade”

Flushing and Refreshing Objects

• Processing methods cache the SQL query generated in the Session object
• Queries are not automatically flushed out to the DB
–For load() and get() stale data as the queries are cached
–Session is flushed out automatically when Transaction commit() is used
–Flush() method can be explicitly called
–setFlushMode() sets the flush mode of the session to a specified value
• refresh() reloads the object from DB

Detached Objects

•Applications retrieve objects from one session
• Modify the object and update it using a new session
–To avoid keeping the DB connection open
• save() called on a new session, inserts a new record
• saveOrUpdate() or update() updates the record
• lock() method attaches the object with the new session
–However the object needs to be unmodified
–LockModecan be set, but depends on the DB.

Need for Caching

• Persisting and load objects is performed a number of times in an application
• Performance plays a major role in multi-user and web applications
• Object availability and DB visits has an impact on the performance to an extent
• Caching of Objects and queries makes the system more responsive

Caching in Hibernate

• Hibernate provides multi-level caching scheme
• Session object provides the first-level cache
–Acts as a cache when object is pulled from the DB
–Object available in the memory if the application needs it
–Hibernate delays update as long as possible

Second-level Cache

• Possible to configure a JVM-level or SessionFactory-level-class cache
• Hibernate delegates some caching of specific classes to second level cache
• Objects cache here are available across the sessions
• Caches are never aware of changes made to the persistent store by another application

No comments:

Post a Comment