Thursday 20 December 2012

Transaction Management in Hibernate


Transaction Management in Hibernate

Transaction: Transaction simply means a unit of work, which is atomic. If only one step fails, then the whole unit of work fails.

When we consider database, Transaction groups a set of statements/commands 
which gets committed together.If a single statement fails, whole work will be 
rolled back.

Transactions can be described using ACID criteria.
ACID means:
A : Atomicity: In a Transaction If only one step fails, the whole unit of work must fail.This is known as atomicity
C : Consistency : The Transactions operate on Consistent data. I.e. This data is hidden from other concurrently running transactions. The data is clean and consistent.
I : Isolation: It means when a transaction is being executed, it will not be visible to other concurrently running transactions.This means, any changes done to the existing data during a transaction, before transaction finishes, is not visible to other active transactions. They work on consistent data.
D : Durable: Also the changes done in a transaction are durable. Even if server / system fails after a transaction, the changes done by a successful transaction are permanent / persistent.

So a database transactions involve a set of SQL statements, which either succeeds or fails. If any one of the statement fails in between,the execution of subsequent statements are aborted and all changes done by the previous SQL statements will be rolled back.
In complex applications, which involve different database actions, one should set boundries for a transaction. This means beginning and end of the transaction should be decided. This is called 'Transaction demarcation'. If an error occurs (either while executing operations or when committing the transaction), you have to roll back the transaction to leave the data in a consistent state.

This can be done in 2 ways.
1. In a programmatic manner by explicitly setting boundaries in code or using JTA API.
2. Setting Transaction boundaries by declarative manner, specifying transaction boundaries to managed containers like EJB container.

Transaction demarcation using code:
This technique requires extra coding. In simple JDBC, transactions can begin by calling setAutoCommit(false) on a JDBC Connection and end it by calling commit(). You may, at any time, force an immediate rollback by calling rollback().
In a system that manipulates data in several databases, a transaction may involves access to more than one resource. In this case, you can't achieve atomicity with JDBC alone. You need a transaction manager that can handle several resources in one system transaction. Such transaction-processing systems expose the Java Transaction API (JTA) for interaction with the developer. The main API in JTA is the UserTransaction interface with methods to begin() and commit() a system transaction.

In Hibernate, it has Transaction interface. They work on top of JTA. The main benefit of using Transaction interface, is tight integration with persistence context management-for example, a Session
is flushed automatically when you commit.
Hibernate Example:
     Session session = null;
     Transaction tx = null;
        try {
                  session = sessionFactory.openSession();
                  tx = session.beginTransaction();
                  doTheAction(session);
                  tx.commit();
            }
         catch (RuntimeException ex) 
                  {
                       tx.rollback();
                  } 
             finally
                 {
                      session.close();
                 }

In the above example, a transaction started by session.beginTransaction(). In Hibernate A JDBC Connection from the connection pool is obtained only when the database transaction begins. The call to beginTransaction() translates into setAutoCommit(false) on the fresh JDBC Connection. When you call commit() on the Transaction, Session is flushed. After you commit the transaction (or roll it back), the database connection is released.



Tuesday 11 December 2012

Differences between Hibernate 2.x and Hibernate 3.x


Some of Key Points Hibernate 2.x V Hibernate 3.x:
  •    Hibernet2.x version increases to Hibernet3.x, that is include
       more features and bug fixes.
  •    Hibernate 3.0 is not source-compatible with Hibernate 2.1.
  •    The changes made in Hibernet3.0 were carefully designed to
       allow straightforward migration of both code and metadata.
  •    It is possible to run Hibernate 2.x and Hibernate 3.x side by
       side in the
    same application. 
Some of Changes made in Hibernate3.x compared with Hibernet2.x:

API Changes:
  •  The Hibernate3 package structure is rooted at org.hibernate 
     instead of net.sf.hibernate.This renaming was done to allow
     Hibernate2 and Hibernate3 to run side by side in the same
     application.
  •  Certain interfaces that have been deprecated in Hibernate3
     were moved to the org.hibernate.classic package.
  •  HibernateException and all other Hibernate exceptions are
     changed in Hibernate3 as a unchecked runtime exceptions.
  •  Compared to Hibernate2 , Hibernate3 provides the
     ParameterizedType interface to allow better re-useability of
     user type implementations.
  •  Hibernate3.x wraps Blob and Clob instances, to allow classes
     with a property of type Blob or Clob
    to be detached,serialized,
     deserialized, and passed to merge(). Hibernate2.x not
     supported this feature.
Metadata Changes :
  • In Hibernate2.x it is best practice to map almost all classes and collections using lazy="true",that is in Hibernate3.x the default feature. In hibernate2.x applications will need to explicitly specify
    lazy="false" on all non-lazy class and collection mappings.
  • In hibernet 3.x The outer-join attribute is deprecated.Use fetch="join" and fetch="select" instead  of outer-join="true" and outer-join="false".
  • The <index> element is semi-deprecated, <list-index> and <map-key> are now preferred In hibernate3.x.
          <map-key-many-to-many> is preferred to <key-many-to-many>.      
          <composite-map-key> is preferred to <composite-index>.
  • DTD reference in hbm XML files is changed in Hibernate 3.x when compared to Hibernate2.x.
 
Query Language Changes :
  •  Hibernate3 comes with a brand-new, ANTLR-based 
     HQL/SQL query translator. However, the Hibernate 2.1
    query 
     parser is still available.
  •  The query parser may be selected by setting the Hibernate 
     property  hibernate.query.factory_class.

Main Advantage Of Hibernates :
  •  Hibernate supports Inheritance, Associations, Collections.
  •   In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws,but in hibernate we only have    Un-checked exceptions (From Hibernate 3.x), so no need to write try, catch or no need to write throws.
  •   Hibernate has capability to generate primary keys automatically while we are storing the records  into database.
  •   Hibernate has its own query language, i.e hibernate query language which is database independent.
  •   While we are inserting any record, if we don't have any particular table in the database, JDBC will rises an error like "View notexist",and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us
  •  Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.
Disadvantages Of Hibernates :
  • Hibernate is little slower than pure JDBC, actually the reason  being hibernate used to generate many hibernate used to gener ate many SQL statements in run time.
  •   Boilerplate code issue, actually we need to write same code in several files in the same application.