ABOUT
TAGS
Hibernate
n+1 selects problem:

The biggest performance killer in applications that persist objects to SQL databases is the n+1 selects problem. For this map all the associations for lazy initialization, this means lazy="true" and fetch="join" ( this is default in Hibernate 3 ).
Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT.
This is the only way to avoid retrieving all objects in the database in every transaction.

More about declaring and defining primary keys in mapping definition file:
For a primary key column
<id name="id" type="long" column="ID" >
<generator class="native"/> // there are several other types of this class ( for ex: sequence, increment, etc )
</id>
For a composite primary key
<composite-id>
<key-property name="deptId" type="string" column="DEPT_ID" />
<key-property name="IdCardNo" type="string" column="ID_CARD_NO"/>
</composite-id>

Ten reasons to love Hibernate
  1.Dynamic UPDATE generation – figure out which columns changed
  2.Trying new databases
  3.Traversing associations
  4.Optimistic Locking
  5.ID generation
  6.No more DTOs
  7.Query result paging
  8.Automatic dirty checking
  9.Good price - free to use it.
10.Good documentation

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

    * Session interface
    * SessionFactory interface
    * Configuration interface
    * Transaction interface
    * Query and Criteria interfaces


What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

About Hibernate-reveng configuration file
An eclipse plugin used to generate the hibernate mapping files (.hbm).

Levels of Caching
First Level:
       This is at the session scope level.
Second Level:
       The first step is to choose a cache provider. EHCache, which is the default cache provider for Hibernate.
You can as well Cache queries:
       If you are running the same query in two different sessions,
       for ex:
               <hibernate-configuration>
                       <session-factory>
                       ...
                       <property name="cache.use_query_cache">true</property>
                       ...
                       </session-factory>
               </hibernate-configuration>
Jars needed in classpath:
       lib/hibernate3.jar
       lib/antlr.jar
       lib/asm.jar
       lib/asm-attrs.jars
       lib/cglib.jar
       lib/commons-collections.jar
       lib/commons-logging.jar
       lib/dom4j.jar
       lib/ehcache.jar
       lib/jta.jar
       lib/log4j.jar

Configuration: There are total 3 ways to configure Hibernate ( programmatic, xml and properties file configurations , widely used is xml configuration )
XML Config: hibernate.cfg.xml is where all the hibernate configurations are defined.
Either you can mention the datasource created in application server , or the driver class and url in this xml file. This also contains the dialect entry. Most importantly under the "mapping resource" tag contains the .hbm file.

Programmatic config:
Using the configuration class , you need to set all the properties, for example
       Configuration configuration = new Configuration()
       .addResource() // here is where the .hbm files need to be mentioned
       .setProperty();
       SessionFactory factory = configuration.buildSessionFactory();
if there more hbm files, you can jar them and use the method .addJar(new File("hbmmapping.jar")) instead of addResource().

Mapping definition:
For a Book object, we create a xml file Book.hbm.xml. This is called the mapping definition. Here is where each variable from the Object class is mapped to the column of the database table.

How to load the hibernate configuration:
Click here to view the sample file
Declaring transactions:

Session session = factory.openSession();
Transaction tx = null;
try {
       tx = session.beginTransaction();
       // Using the session to persist objects
       tx.commit();
} catch (HibernateException e) {
       if (tx != null) tx.rollback();
       throw e;
} finally {
       session.close();
}

If you don't want to define transaction in your application, you can set the “autocommit” property to true (which is false by default) in your XML configuration file.
The tag for this is <property name="connection.autocommit">true</property>
In this case, each single update will be committed to the database immediately. Important thing here is "you must flush your session before closing it". The reason being, Hibernate won't write the changes to database immediately, it will queue all the statements for increase in performance.

session.flush();
Retrieving objects:
Given an isbn id, there are 2 ways to ge the book instance from database.
Book book = (Book) session.load(Book.class, isbn);
       or
Book book = (Book) session.get(Book.class, isbn);

Difference between load and get methods

load()
get()
If the given Id is not found, the following exception is thrown "org.hibernate.ObjectNotFoundException"
this will return a null object
this return a proxy by default, and database wont be hit until the proxy is first invoked
will hit the database immediately
Saving objects to database:

For saving a newly created object, use session.save(object).
For updating an existing object, use session.update(object).
For deleting an existing object, use session.delete(object).

To the SQL statements issued by Hibernate:
Set the “show_sql” property to true in the XML configuration; <property name="show_sql">true</property>
Opening and closing sessions:

Session session = factory.openSession();
try {
       // Using the session to retrieve objects
} finally {
       session.close();
}
Narendra Kumar Dantala
A J2EE Developer
Having a masters degree in Computational Science, working in Java, developed applications on different domains such as Finanical Services, B2B, Banking, Utility...