Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Thursday, July 7, 2011

Pre-requisites for hibernate

We need following tools and binaries:

1.The IDE used is Eclipse Indigo(latest one while writing this post).
2.Hibernate binaries(Hibernate Core 3.6.5 final) can be downloaded from here
3.Database HSQLDB 1.9 or H2 database or any other database

The next step is unzip Hibernate Tools 3.2.4 GA and put features and plugins contents to features and plugins directory of Eclipse Galileo. Ensure you have closed Eclipse IDE prior to this step and once you are done with copying part then restart the Eclipse Galileo.


You have to ensure following JARs have been included in the project:

-hibernate3.jar(contains all core Hibernate files)
-antlr
-commons-collections
-dom4j
-javassist
-jta
-slf4j
-slf4j-simple-1.5.8.jar(download it from here)
-hsqldb.jar(used for connecting to HSQL Database) or h2.jar (already present in bin folder of h2 downloaded zip)

Tuesday, July 5, 2011

Many-to-one, bidirectional Associations

In this case we allow navigation in both directions between the two classes. On the Many side it is a standard java reference. on the One side it is a collection. However, the two associations are not independent of each other but rather, one is the inverse of the other and the same foreign key column is used for both associations. Thus our Lecturer object now has a property which is a collection of Student objects while the Student objects have a properties which refers to the Student's supervising Lecturer.

A Many-to-One, bidirectional Association

To achieve this, we start by using the many-to-one element as before in the mapping file for the Student class, and the Set element as before in the mapping file for the Lecturer class, ensuring that both associations use the same column in Student's table to encode the association. Then we add a new attribute, inverse="true" to the set element in Lecturer's mapping file. Without this, adding a new Student as an advisee to a Lecturer would trigger Hibernate to set the foreign key column of the Student table twice: once for each association that has been changed. The inverse attribute tells hibernate that Student owns the association and that Hibernate should not trigger updates of the foreign key column when it changes on the Lecturer side.
Thus the mapping file for Lecturer looks like this:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
    <class name="Lecturer" table="lecturers">
        <id name="id" column="lecturer_id">
            <generator class="sequence"/>
        </id>
        <version name="version" column="version"/>
        <property name="name" column="name"/>
        <set name="advisees" inverse="true" cascade="save-update" lazy="true">
            <key column="lecturer_id"/>
            <one-to-many class="Student"/>
        </set>
    </class>
</hibernate-mapping>

The mapping file for student is as follows:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
    <class name="Student" table="students">
        <id name="id" column="student_id">
            <generator class="sequence"/>
        </id>
        <version name="version" column="version"/> 
        <property name="name" column="name"/>
        <property name="regNo" column="reg_no"/>
        <many-to-one name="advisor" column="lecturer_id" cascade="save-update"/>
    </class>
</hibernate-mapping>

Now all the programmer has to do is to ensure that, when the Lecturer's advisee property property is changed, the corresponding correct changes are made to the appropriate Student's advisor property. So long as both are done together, the Java object graph will be correct and the correct update on disk will be made as well. Furthermore, since the association belongs to the Student, there will never be an insert of a Student record with a null Lecturer foreign key if the Student has an advisor, thus avoiding not-null constraint breaking. To ensure that these updates are made together, it is usual to add some convenience methods: in Lecturer, change the getAdvisees() and setAdvisees() methods to private and add a convenience method to update the object graph correctly when adding a new Student advisee to a Lecturer:

public void addAdvisee(Student st)
    {
        Lecturer oldAdvisor = st.getAdvisor() ;
        if (oldAdvisor != this)
        {
            if (oldAdvisor != null)
                oldAdvisor.getAdvisees().remove(st) ;
            st.setAdvisor(this);
            advisees.add(st) ;
        }
    }

Note how we are careful to correctly handle removal of a Student from a previous advising Lecturer before adding it to this one. Whether you need to do something similar for your code will depend on your detailed design.
If we have a true composition relationship, i.e., a parent-child relationship where if the parent gets deleted then the child should also be deleted etc., then we should change the cascade attribute on the set element in the Lecturer mapping file to be all-delete-orphan.

One-to-Many, Unidirectional Associations

This relationship is essentially the same as Many to One relation, Unidirectional relation , but now we choose the opposite direction for navigating the connection. See here for Many to one unidirectional relation.

Thus our Lecturer object now has a property which is a collection of Student objects while the Student objects have no properties which refer to their supervising Lecturer.

A One-to-Many, Unidirectional Association

As far as the database is concerned, there is no difference between this and the unidirectional many-to-one association: there will still be a single column in the table holding the Student objects that contains a foreign key into the table holding the Lecturer objects.
Now that entities are being stored in collections, it becomes critical that you have appropriately implemented equals and hashCode methods for those entities. In particular, you should ensure that these methods are independent of the generated surrogate keys and that trivial changes to the object do not effect the methods while the objects are in the collections.
The simplest collection, for our purposes, is a Set. To create the association, we add a Set valued property to Lecturer
 
<set name="advisees" cascade="save-update" lazy="true">
    <key column="lecturer_id"/>
    <one-to-many class="Student"/>
</set>

Here, we define a property of Lecturer which is Set valued. The name of the property is advisees. This property is to capture a one-to-many association to the Student class and it this association is to be implemented in the database as a foreign key to the table holding Lecturer objects stored in the column lecturer_id in the table holding Student objects.
There are a number of constraints imposed by the use of this one-to-many association which arises from the fact that it is represented by this "reverse" link from the contained object side of the association:
  1. From a Java point of view, we could potentially have two different Lecturer objects, both of which have the same Student object in their container. However, this is not possible for a one-to-many association because, in the database, each Student row refers to the single Lecturer row which contains it. If you want the true Java semantics, you have to represent the association as a many-to-many one.
  2. You cannot have the same object multiple times in the same collection. This is obvious when the collection property is of type Set, but one could use other types, such as List. However, the implementation of association by the reverse foreign key makes this impossible. Again, a many-to-many association can provide the appropriate semantics

Finally, there is the question of why one-to-many associations between entities cause problems. Consider the following code:
tx = session.beginTransaction();
Lecturer lect = new Lecturer("Gordon Brown") ;
lect.getAdvisees().add(new Student("Tony Blair")) ;
lect.getAdvisees().add(new Student("Michael Howard")) ;
session.save(lect);
tx.commit();

Note that the association belongs to the Lecturer class (as it is defined in Lecturer's mapping file). This means that adding a student to a lecturer's advisees is considered an operation on a lecturer, not on a student. Thus the SQL statements that would be generated for the above statements would include an insert for the lecturer object, together with an insert each for the two connected student objects (because the students are referred to by the lecturer and we have put the cascade="save-update" declaration in the Lecturer's mapping file. But because the association does not belong to the students, the saving of the students would not set the foreign key value to the advising lecture. Thus there would be two extra update statements for adding the lecturer's foreign key value into the student records. These extra two update statements are not just an efficiency problem: If every student should have a supervisor, then we would like to add the not-null="true" attribute to the key element in the mapping file for the association. However this would cause errors as the above sequence of inserts and updates does insert nulls (if only to immediately update them) where they should never occur.

The solution is to only create such one-to-many associations as the inverse end of a bidirectional many-to-one association. This gives ownership of the association to the Student end and, as we see below, leads to the foreign key being created as part of the initial insert of the Student record instead of after it as a consequence of the Lecturer insert.

Mapping Entities with Inheritance

Again there are a number of ways Hibernate can handle inheritance. These are based on the standard techniques for reducing generalisation hierarchies in entity-relationship diagrams.

The simplest is to use one table for the whole hierarchy. With this design, each row of the table can hold an object of any type from the hierarchy. There is one column for each of the properties in the union of the sets of properties of all the classes in the hierarchy and there is one discriminator column which contains a value (usually of type string, character or integer) used to tell which actual type of object is stored in this particular row. One normally does not make this discriminator a property of the class: it is used only by Hibernate to record and detect the type of the object that a row represents.
An Inheritance Class Hierarchy


<class name="Person" table="people" discriminator-value="P">
    <id name="id" column="id" type="long">
        <generator class="sequence"/>
    </id>
    <version  name="version"         column="version"/>
    <discriminator column="subclass" type="character"/>
    <property name="dateOfBirth"     column="dob" type="date"/>
    <property name="name"/>
    <property name="gender"/>
    <subclass name="Lecturer" discriminator-value="L">
        <property name="office" type="string"/>
        <property name="telephone" type="string"/>
    </subclass>
    <subclass name="Student" discriminator-value="D">
        <property name="studentID" type="integer"/>
    </subclass>
</class>

Here one may not specify any of the subclass fields as not null because the corresponding column will be null in the table for any object of the hierarchy which is not of the subclass that contains the relevant property for that column.

Many-to-One, Unidirectional Associations

This corresponds to the standard Java reference to one object from another.
A Many-to-One, Unidirectional Association

In the diagram above, we represent the relationship between students and their thesis supervisors. In this design, a student can have no more than one supervisor but may not (yet) have any. However, a lecturer may have any number, including zero, of students to supervise. Furthermore, we only allow a one directional link: Student has a property (say getSupervisor/setSupervisor) but there is no direct way, starting with a Lecturer object, to find the students that the lecturer supervises.
If we start with the simple, non-related, base entity mapping files for Student and Lecturer, we add this association by adding the following, as a sub-element of the class element, to the mapping file for Student:

<many-to-one name="supervisor"    column="supervisor"/>

This element acts very much like a normal property element in that it defines the mapping between the supervisor property of Student and the column in the students table. However, it also sets up the relationship so that, after getting a Student object from the database, if we use the supervisor accessor of that Student object, we will get the corresponding Lecturer object (or a proxy thereof if we have enabled lazy loading of the Lecturer objects). Finally, it ensures that the underlying database is created with a foreign key constraint that the supervisor column is a foreign key into the lecturers table.
As things stand, there is now a question of what you want the cascade behaviour of the relationship to be (see the section on cascade above). Without adding the optional cascade attribute to the many-to-one element, then the Lecturer object on the other end of the association is ignored when the Student object is saved, updated, deleted or when its supervisor property is reset away from it. Certainly we would not want the lecturer to be removed from the database when the student is deleted or when the student no longer has that lecturer as his or her supervisor; so none of the delete or all options are appropriate. But what about save-update?. There are two scenarios under which this might have an effect:
  1. If you create a new (transient) lecturer and make a persistent student refer to it. In fact, for this particular object design, one would never do such a thing: the obvious semantics of the situation dictate that you cannot just invent new lecturers on demand: you would always have to have the lecturer as a currently existing object in the database before setting the student's supervisor property to that lecturer. Since the scenario will never arise, this is neither a vote for or against using the save-update option.
  2. If the Student, and associated Lecturer objects were detached, and now you reattach the Student object, then you need the save-update option if you want the Lecturer object to be reattached automatically. Without that, you need to reattach it directly yourself — an easy task to overlook and therefore a source of bugs. This therefore, is a vote for set the cascade="save-update" option.

Note that you can specify unique="true" as an attribute of the many-to-one element. This has the effect of disallowing the possibility of having two student rows with the same supervisor values, i.e., turning the "*" on the Student side of the class diagram into a "0..1" or limiting each lecturer to having at most one supervisee. Similarly, specifying not-null="true" adds the requirement that every student must have a valid supervisor, i.e., it changes the "0..1" on the Lecturer side of the diagram to a "1".

Cascading Persistence in Hibernate

We have said, a number of times, that when an object is made persistent, that the objects it refers to are also made persistent. This was an oversimplification. In the mapping files for the classes, there is an attribute, cascade that lets us control how much, or how little, of a reference graph gets automatically persisted, deleted or updated. The values that it can be set to, and their meanings, are as follows:
  • none: no automatic action on the referenced object takes place.
  • save-update: automatically save or update the referenced object when the referencing object is saved or the transaction commits.
    delete: automatically delete the referenced object when delete() is called on the referencing object. Note that, if the referencing object is not deleted but merely removes its reference to the referenced object, then this option will not do anything and, potentially, a garbage (or orphan) object will be left in the database.
  • delete-orphan: automatically delete any object for whom the reference has been removed from the referencing object.
  • all: take the same actions as save-update and delete but not that of delete-orphan.
  • all-delete-orphan: take the same action as save-update, delete and delete-orphan.

Requirements for object to become Hibernate Object

A Hibernate object, suitable for mapping into a database, is a normal java bean with a number of extra requirements.
  • There must be a default constructor for the class.
  • There must be accessors and mutators for all the instance variables of the class. Actually this is overstating the requirement but is a good base rule: read the Hibernate documentation for the full details.
  • The class should implement Serializable. Strictly speaking, this is not a requirement. However, in practice you will normally want your Hibernate objects to be serializable so that they can be (potentially) migrated around a multiprocessor cluster or saved and restored across a web server reboot etc.
  • The class should have an id instance variable, usually of type Long. Again this is not a true requirement but it is recommended to use automatically generated surrogate keys and, if so, to use an instance variable called id to hold it. Certainly, alternatives are possible.
  • The mutator for the id property should be private, not public. Again not a requirement but good practice. You should never update the id property directly but rather rely on Hibernate updating it for you. In practice, it is the value of this field that Hibernate uses to decide if an object has been mapped to a database record or not. Change the property yourself and you could seriously confuse Hibernate.
  • You should decide on a business key for the object and implement the equals and hashCode methods for it.
  • You should add any extra type specific constructors (which should leave the id field null) and business rule methods you like.
  • You should not make the class final if you want to be able to use lazy loading for objects of the class.

Saturday, June 25, 2011

What is ORM?

ORM stands for Object-Relational Mapper. It’s mostly used to define a relationship between an object/class and the database table where it’s data should be saved.
Basic idea of Object Relational Mapping(ORM) is converting data between incompatible types in oop languages.When it comes to data bases it is about creating creating virtual data base objects which can be used in object oriented programming.
See the diagram:


Above diagram clearly explains the task of ORM mapping. To get the overall task done first we need to select a good data base driver which create the connection between our program and the data base. this method is efficient than manually create data base connection every where and close the connection.

Friday, June 24, 2011

Why should you use Hibernate?

There are couple of reasons to use hibernate:
Reason 1 - Performance

Hibernate generates very efficient queries very consistently. However, that is only the begining of the performance story. Hibernate employs very agressive, and very intelligent first and second level caching strategy. This is a major factor in acheiving the high scalability.
Hibernate spares you a unnecessary database calls. So all these lookup tables, and rarely changing data can get cached, and much more.
It allows you to cache how much you want, and it can be very intelligent with write-backs. Furthermore, it integrates well with the major open source (OSCache, EHCache, JBossCache, ...) and commercial caching products such as Tangosol giving you an opportunity to use even more sophisticated features that come with these products.

Reason 2 - Effective Cross-Database Portability

Hibernates portability accross the relational databases is amazing.
It is literally one configuration paramter change. You only have to change the database dialect. This property was especially helpful in my previous company because we used to deploy to wide range of databases since had bunch of extra licenses, so we never knew if the DBA manager would allocate us a Sybase or DB2. So we used to develop on MySQL, and then deploy on whatever. The only change was the change of the dialect - one line change in the configuration file.
That was it!

Reason 3 - Developers' Productivity

I have to admit that Hibernate ,like other sophisticated frameworks, has a steep, but short learning curve, but once you got it - you got it. It becomes a breeze to work with, and it feels like a magic.

But who shouldn't use hibernate?
If your project is using lots of stored procedures, please don't use Hibernate.

Fetching strategies in hibernate

join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is loaded.
Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
"Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)
Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.
"No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.
Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
We use fetch to tune performance. We may use lazy to define a contract for what data is always available in any detached instance of a particular class.

[Source:Hibernate Reference Documentation]

What are core interfaces for Hibernate framework?

Most Hibernate-related application code primarily interacts with four interfaces provided by Hibernate Core:
org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query

The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not thread safe.

The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database.

The Criteria provides a provision for conditional search over the resultset.One can retrieve entities by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually obtained via the factory methods on Restrictions.
Query represents object oriented representation of a Hibernate query. A Query instance is obtained by calling Session.createQuery().

More Hibernate Questions

Question: What are common mechanisms of configuring Hibernate?
Answer: 1. By placing hibernate.properties file in the classpath.
2. Including elements in hibernate.cfg.xml in the classpath.

Question:How can you create a primary key using Hibernate?
Answer: The 'id' tag in .hbm file corresponds to primary key of the table:
Here Id ="empid", that will act as primary key of the table "EMPLOYEE".

Question: In how many ways one can map files to be configured in Hibernate?
Answer: 1. Either mapping files are added to configuration in the application code or,
2.hibernate.cfg.xml can be used for configuring in .

Question: How to set Hibernate to log all generated SQL to the console?
Answer: By setting the hibernate.show_sql property to true.

Question: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
Answer: The settings of the XML configuration file will override the settings used in the properties.

Question: What methods must the persistent classes implement in Hibernate?
Answer: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables.

Question: How can Hibernate be configured to access an instance variable directly and not through a setter method?
Answer: By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

Question: How to declare mappings for multiple classes in one mapping file?
Answer:Use multiple elements. But, the recommended practice is to use one mapping file per persistent class.

Question: How are the individual properties mapped to different table columns?
Answer: By using multiple elements inside the element.

Question: What are derived properties?
Answer: The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

Question: How can you make a property be read from the database but not modified in anyway (make it immutable)?
Answer: Use insert="false" and update="false" attributes.

Question: How can a whole class be mapped as immutable?
Answer: By using the mutable="false" attribute in the class mapping.

Friday, June 17, 2011

How to setup H2 database for database connections in java?

Download H2 database
Download H2 database from - H2 download, I downloaded the platform independent version. Extract the zip to some directory.
Run the H2 engine
Now migrate to bin extracted folder, and go to bin folder. Double click on h2.bat and the database engine starts.
Add the jars 
Add H2 jar present in the same bin folder to the java project and add following class to the project and run it.

Now test the code:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class H2Test
{
  public static void main( String args[] ) throws Exception
  {
    Class.forName( "org.h2.Driver" );
    Connection conn = null;
    Statement stmt = null;

    try
    {
      conn = DriverManager.getConnection( "jdbc:h2:file:db/test", "sa", "" );
      stmt = conn.createStatement();
      stmt.executeUpdate( "create table person(name varchar(10));" );
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
    finally
    {
      if( stmt != null )
      {
        try
        {
          stmt.close();
          System.out.println("Test done");
        }
        catch( Exception e )
        {
          e.printStackTrace();
        }
      }

      if( conn != null )
      {
        conn.close();
      }

    }

  }
}


Wednesday, June 15, 2011

Hibernate generator classes

In Hibernate the optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class.

If any parameters are required to configure or initialize the generator instance, they are passed using the <param>element.

<id name="id" type="long" column="cat_id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
</generator>
</id>



All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specialized implementations. However, Hibernate provides a range of built-in implementations. There are shortcut names for the built-in generators:


increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.

select

retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

sequence-identity

a specialized sequence generation strategy which utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to actually return the generated identifier value as part of the insert statement execution. This strategy is only known to be supported on Oracle 10g drivers targetted for JDK 1.4. Note comments on these insert statements are disabled due to a bug in the Oracle drivers.



    Reference




    Extracted from Hibernate online official tutorials



    List of Cache Provider in Hibernate and their concurrency support details


    Here in this port you can find the list of Cache providers and their Concurrency support details. (Exerted from Official Hibernate Tutorial)
    EHCache (Easy Hibernate Cache)
    (org.hibernate.cache.EhCacheProvider)
    • It is fast.
    • lightweight.
    • Easy-to-use.
    • Supports read-only and read/write caching.
    • Supports memory-based and disk-based caching.
    • Does not support clustering.
    OSCache (Open Symphony Cache)
    (org.hibernate.cache.OSCacheProvider)
    • It is a powerful .
    • flexible package
    • supports read-only and read/write caching.
    • Supports memory- based and disk-based caching.
    • Provides basic support for clustering via either JavaGroups or JMS.
    SwarmCache (org.hibernate.cache.SwarmCacheProvider)
    • is a cluster-based caching.
    • supports read-only or nonstrict read/write caching .
    • appropriate for applications those have more read operations than write operations.
    JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)
    • is a powerful replicated and transactional cache.
    • useful when we need a true transaction-capable caching architecture .
    Cache providers.
    Cache
    Provider class
    Type
    Cluster Safe
    Query Cache Supported
    Hashtable (not intended for production use)
    org.hibernate.cache.
    HashtableCache
    Provider
    memory
    yes
    EHCache
    org.hibernate.cache.
    EhCacheProvider
    memory, disk
    yes
    OSCache
    org.hibernate.cache.
    OSCacheProvider
    memory, disk
    yes
    SwarmCache
    org.hibernate.cache.
    SwarmCacheProvider
    clustered (ip multicast)
    yes (clustered invalidation)
    yes (clock sync req.)
    JBoss Cache 1.x
    org.hibernate.cache.
    TreeCacheProvider
    clustered (ip multicast), transactional
    yes (replication)
    yes (clock sync req.)
    JBoss Cache 2
    org.hibernate.cache.
    jbc2.JBossCache
    RegionFactory
    clustered (ip multicast), transactional
    yes (replication or invalidation)
    yes (clock sync req.)
    Cache Concurrency Strategy Support
    Cache
    read-only
    nonstrict-read-write
    read-write
    transactional
    Hashtable (not intended for production use)
    yes
    yes
    yes
    EHCache
    yes
    yes
    yes
    OSCache
    yes
    yes
    yes
    SwarmCache
    yes
    yes
    JBoss Cache 1.x
    yes
    yes
    JBoss Cache 2
    yes
    yes

    Chitika