Five ‘s Weblog

November 11, 2007

The process-level cache in Hibernate

Filed under: ORM — by powerdream5 @ 8:03 pm
Tags: , ,

11_11_1_2007.jpg

        Hibernate has two kinds of cache, which are the first-level cache and the second-level cache. We also call the first-leve cache session cache, and the second-level cache process-level cache. The first-level cache is mandatory and can’t be turned off; However, the second-level cache in Hibernate is optional. Because the process-level cache caches objects across sessions and has process or cluster scope, in some situation, turning on the process-level cache can improve the performance of the application. In fact, before accessing the database to load an object, Hibernate will first look in the Session cache and then in the process-level cache.

       The process-level cache is best used to store objects that change relatively infrequently, and it is set up in two steps. First, you have to decide which concurrency strategy to use. After that, you configure cache expiration and physical cache attribtes using the cache provider. Hibernate supports a variety of caching strategies including:
read-only : which is suitable for objects which never changes. Use if for reference data only.
read-write : which is suitable for objects that are modified by the application.

      To cache these classes in the process-level cache, we must use the <cache> element in the O/R mapping. For example:
<class name=”?” talbe=”?”>
      <cache usage=”read-wirte” />
      …
</class>

      The usage=”read-write” attribute specifies that instances of this class are sometimes updated by the application. One thing needed to remember is that you must enable lazy loading for relationships that are from objects that not cached to objects that are cached to ensure that the applications uses the cache.
<class name=”?” talbe=”?”>
      <cache usage=”read-wirte” />
       …

       <set name=”?” lazy=”true”>
                /*collections require their own <cache> element*/
               <cache usage=”read-only” />
                …
        </set>
</class>

11_11_2_2007.jpg

November 9, 2007

Eager loading in Hibernate

Filed under: ORM — by powerdream5 @ 5:50 pm
Tags: , , ,

      In default, Hibernate adopts the mechanism of lazy loading to load objects from databases. Lazy loading contributes a lot to improve the performance of an application by limiting the amount of objects that will be needed. In contrast to lazy loading, eager loading loads the full objects tree once. Because eager loads multiple related objects with a single SELECT statement instead of using multiple SELECT statements, therefore in some situations, eager loads can also improve the performance of the application by reducing the times of accessing the database.

     There are two ways to configure eager loading in Hibernate. They are staticly eager loading and dynamically eager loading respectively. If the application always traverses a relationship, you might want to configure it to be always staticly eager loaded. Conversely, you might want to dynamically configure eager loading for relationships that are only traversed by the application when handling particular requests.

     One way to configure static eager loading is specifying a value for the fetch attribute of the relationship’s mapping element. 
     This attribute can have one of two values:
     select: Lazily load the referenced object or collection with a separate SQL SELECT statement. It is the default value
     join: Eagerly load the referenced object or collection using an outer join

<hibernate-mapping>
     <class name=”?” table=”?”>
          <many-to-one name=”?” fetch=”join” column=”?” />
     </class>
</hibernate-mapping>

      To configure dynamical eager loading, you must use queries with fetch joins.
<hibernate-mapping>
      …
      <query name=”queryName”>
            <![CDATA[
                 from student s
                 left outer join fetch s.classID as c
                 left outer join fetch c.className
                 where s.id = ?
            ]]>
       </query>
     ….
</hibernate-mapping>

     Finally, take a note that Hibernate has a rule that a class can only have at most one collection loaded using an outer join. This is to prevent inefficient queries that return the Cartesian product of too large collections.

11_9_2_2007.jpg

November 7, 2007

Transaction Concurrency (2)

Filed under: Five's thought — by powerdream5 @ 11:13 pm
Tags: , ,

       As mentioned in the article Transaction Concurrentcy(1), most application choose read committed as the isolation level. The reason is that no matter whether there is concurrency occuring, serializable and repeatable read need to lock the rows in the database, which cause the reduction in the system performance, especially for these system where concurrency doesn’t happen frequently. However, Read committed cannot avert unrepeatable read and Second lost updates problem, therefore, we need to use optimistic locking or pessimistic locking to make up!

11_7_1_2007.jpg

      Today, I am going to make a brief introduction to optimistic locking. Optimistic locking is based on the assumption that most database transaction don’t conflict with other transactions. In fact, optimistic locking doesn’t actually lock anything. Instead, when a transaction updates a row it verifies that the row has not been changed or deleted by a different transaction since it was read. If it has, the transaction is typically rolled back and retried.

     Usually, there are three methods to realize optimistic locking. The first one is adding a version column to the tables in the database. The second one is adding a timestamp column, and the third one is to compare current values of the columns with their previously read values. Commonly, we prefer the vrsion column to the other two methods, since the third method makes the sql sentences too complicated and the second method is not suitable for any case.

     There is a sql sentence using version column:
     Update ACTIVITIES Set PLACE = ‘?’ WHERE ACTIVITY_ID=? AND VERSION = ?;

     The following is an simple example to show how to configure optimistic locking realized by version column. It is pretty easy!

<hibernate-mapping>
      <class name=”**” table=”**”>
              <id name=”*” column=”*”>
                    <generator class=”*” />
              </id>
              <version name=”version” column=”VERSION” />
      </class>
</hibernate-mapping>

11_7_2_2007.jpg

October 29, 2007

Autowire in Spring

Filed under: Spring — by powerdream5 @ 8:32 pm
Tags: , , , ,

         At the beginning, let’s talk about the function of autowire in spring briefly. In order to save the programmers’ time and effort in writing the spring configuration files by hand, Spring framework introduces the autowire function. To be honest, this function is pretty useful sometimes, but I don’t recommend to use it, since it always bring some problems confusing you. In the following, I would like to show you an example to exmplain why I avert autowire.

10_29_2_2007.jpg

        <beans default-autowire=”autodetect”> <!–autowire is the cause of exception–>
                <bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource”>
                       ……
                </bean>
                <bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
                      ……
                </bean>
                     …….
               <bean id=”cronReportTrigger” class=”org.springframework.scheduling.quartz.CronTriggerBean”>
                     ……
               </bean>
               <bean id=”schedulerFactoryBean” class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>
                         <property name=”triggers”>
                               <list>
                                       <ref bean=”cronReportTrigger”/>
                               </list>
                         </property>
               </bean>
         </beans>

        In my example, firstly, I configure Hibernate. In order to execute a method in a specific time, I configure Quartz. Both of the two configuration processes are so easy that you will not come across any obstacles. However, if you set the autowire properties, when you start the server, you would get the exception: “Failure obtaining db row lock: Table ‘hibernate.qrtz_locks’ doesn’t exist“. I believe you must be confused, and you would ask why the SchedulerFactoryBean class has relationship with Hibernate.

        In fact, this exception is caused by the autowire property of Spring. The org.springframework.scheduling.quartz.SchedulerFactoryBean has a method named setDataSource. Because we set the autowire properiy as “autodetect”, and we also configure database source in our application, the spring container will inject this database source into the SchedulerFactoryBean class automatically, then SchedulerFactoryBean class will looking the database for tasks. There is no task in your database, therefore, you get the exception. Fortunately, as soon as you realize the cause of the exception, it is easy to handle it by removing the autowire property. Then, restart your server, things goes well.

         From this example, we can see that the autowire property may bring some problems over our expectation. Therefore, use this property cautiously!

10_29_1_20071.jpg

October 18, 2007

uni-directional or bidirectional ?

Filed under: ORM — by powerdream5 @ 10:52 pm
Tags: , , , ,

        When mapping the domain model to the database schema,  perhaps we often ask ourselves one question: Making a one-to-many relationship uni-directional or making it bidirectional, which is better in performance. Today, I am going to show an example to demonstrate the difference between uni-direction and bidirection. I am using Hibernate framework.

        There is a class named Consumer and a class named CreditAccount, both of which mapped to the consumer and credit_account table respectively. It is obvious that each Consumer has more than one credit account, therefore, the relationship between the two classes is one-to-many. Firstly, I make the relationship uni-directional.

10_18_2_2007.jpg 

the mapping files are listed in the following:

//Consumer.hbm.xml
<hibernate-mapping>
          <class name=”Consumer” table=”consumer”>
                 <id name=”id” column=”CONSUMER_ID”>
                       <generator class=”native” />
                </id>
               <property name=”firstName” type=”string” column=”FIRSTNAME”/>
               <property name=”lastName” type=”string” column=”LASTNAME”/>
               <set name=”creditAccount” table=”credit_account” cascade=”all”>
                      <key column=”CONSUMER_ID”/>
                      <one-to-many class=”CreditAccount” />
              </set>
           </class>
</hibernate-mapping>

//CreditAccount.hbm.xml
<hibernate-mapping>
          <class name=”CreditAccount” table=”credit_account”>
                 <id name=”id” column=”ACCOUNT_ID”>
                         <generator class=”native” />
                 </id>
                 <property name=”accountNumber” type=”string” column=”ACCOUNT_NUMBER”/>
          </class>
</hibernate-mapping>

We try to insert an new account into the database, from the comman window or log files, we can see that two sql setences are executed. There are:
insert into credit_account(ACCOUNT_NUMBER) values(?)
update credit_account set CONSUMER_ID=? where ACCOUNT_ID=?

Now, I am going to make a little change to the CreditAccount class to make the relationship between Consumer and it bidirectional.  Therefore, I also need to change the mapping files. After being changed, they should be:

//Consumer.hbm.xml
<hibernate-mapping>
          <class name=”Consumer” table=”consumer”>
                 <id name=”id” column=”CONSUMER_ID”>
                       <generator class=”native” />
                </id>
               <property name=”firstName” type=”string” column=”FIRSTNAME”/>
               <property name=”lastName” type=”string” column=”LASTNAME”/>

               //make sure to set “inverse=true”
               <set name=”creditAccount” table=”credit_account” cascade=”all” inverse=”true”>
                      <key column=”CONSUMER_ID”/>
                      <one-to-many class=”CreditAccount” />
              </set>
           </class>
</hibernate-mapping>

//CreditAccount.hbm.xml
<hibernate-mapping>
          <class name=”CreditAccount” table=”credit_account”>
                 <id name=”id” column=”ACCOUNT_ID”>
                         <generator class=”native” />
                 </id>
                 <property name=”accountNumber” type=”string” column=”ACCOUNT_NUMBER”/>
                 <many-to-one name=”consumer” class=”Consumer” column=”CONSUMER_ID”>
          </class>
</hibernate-mapping>

Now, if we insert a new account into the database, only one sql sentence will be executed:
insert into credit_account(ACCOUNT_NUMBER,CONSUMER_ID) values(?, ?)

       There is no doubt that bidirection is better than uni-direction in the performance. If the relationship is uni-direction, only one end is going to maintain their relationshop. The other end cannot see any change of the relationship.  Therefore, the first time we need to execute two sql sentences, the first sql sentence inserts the data into the credit_account table (at this time, the system doesn’t know this account belongs to whom), and the second sql help the credit_account table build its relationship with the consumer table. However, both the end of the bidirectional relationship are aware of any changes, therefore, only one sql sentence can finish two tasks: inserting data and mataining the relationship.

        You can download the source files.

10_18_1_2007.jpg

October 14, 2007

Spring DAO!

Filed under: Five's thought — by powerdream5 @ 1:02 am
Tags: , , ,

      Yesterday, I published an article about applying DAO pattern to encapsulate the persistent layer based on Hibernate framework. At the end of that artcile, I figured that we can use spring framework to make an advance to the exaple. In fact, Spring framework also adopts DAO pattern, however, which is different from the original DAO. In order to distinguish them, I want to call them spring DAO and original DAO respectively.

      I found an article in the internet which describes the differences between Spring DAO and original DAO in detail. I do not want to do some repetive work to explain the reason why Spring DAO is better than the other one. But I would like to answer the following two questions with you guys.

10_12_1_2007.jpg

what is DAO template and what is DAO callback in spring framework?
The biggest differences between Spring DAO and original DAO is that Spring DAO is combinded with template method pattern. Because in the process of interactiving with the database, some steps ares invariable, for example, creating the connection and start the transaction. The original DAO does such things over and over again in each mehtod of the data access object. Fortunately, Spring DAO uses the template method pattern to solve this problem. Therefore, the invariable steps and variable steps are separated and encapsulated. So DAO template is the part which contains the invariable steps, and DAO callback is the part which contains the variable steps.

What is HibernateTemplate and What is HibernateDaoSupport?
Spring framework provides template class for Hibernate framework, which helps release the programmer from writing some repetive codes. This template class is called HibernateTemplate. However, sometimes some programer use HibernateTemplate, but some programers use HibernateDaoSupport. What are the differences between them? After reading the code of the class of HibernateDaoSupport, it is easy for us to answer this quesiton.

//HibernateDaoSupport
public abstract class HibernateDaoSupport extends DaoSupport{
      private HibernateTemplate hibernateTemplate;
      public final void setSessionFactory(SessionFactory sessionFactory){
             this.hibernateTemplate = CreateHibernateTemplate(sessionFactory);
     }
    protected HibernateTemplate createHibernateTemplate(
           SessionFactory sessionFactory);{
           return new HibernateTemplate(sessionFactory);
    }
    public final HibernateTemplate getHibernateTemplate(){
          return this.hibernateTemplate;
    }
           …….
}

        It is obvious that HibernateDaoSupport encapsulates HibernateTemplate. In other words, HibernateDaoSupport seems more convenient than HibernateTemplate. We can make our DAO class extends HibernateDaoSupport instead of injecting the instance of HibernateTemplate to each DAO class.

10_12_2_2007.jpg

October 13, 2007

DAO pattern for Hibernate!

Filed under: Programming — by powerdream5 @ 3:20 am
Tags: , ,

        In J2EE field, open source framework is pretty hot. One of the advantages of them is that they are non-intrusive, because  you don’t need to make your classes extend any classes or implement any interfaces from the framework. However, when we use the ORM framework, such as Hibernate or JDO, we still need to use some specific classes of them. Therefore, in order to make the application more extensible, we should encapsulate the persistence layer of the system.

        DAO(data access object) pattern has already been proved to be a good way to seprate the business logic layer and the persistent layer. Today, I want to show an example of applying DAO pattern to Hibernate.

       Usually, a typical DAO pattern contains a factory class, some DAO interfaces and some DAO classes which implement those interface. Now, Let’s take a blog system for an example. Because I just want to show the structure, I will not present the detail of each class.

10_11_1_2007.gif

      Firstly, we define the factory class:

public class DAOFactory{
        private static DAOFactory daoFactory;
        static{
               daoFactory = new DAOFactory();
        }
        //Define the factory method, return the instance of specific classes
        public DAOFactory getInstance(){
               return daoFactory;
        }
        public BlogDAO getBlogDAO(){
               return new BlogDAOImpl();
        }
         public BlogDAO getCommentDAO(){
               return new CommentDAOImpl();
        }
}

       Secondly, we define the DAO interfaces. The purpose of interfaces is to make our applicaiton more extensible. For example, if we want to change the hibernate framework to the JDO framework in the future, we don’t need to make any change to the business logic, just changing the implementation of the interface works well.

//Data access object interface 
public interface BlogDAO{
      //Blog are an persistence class
      //define the method for inserting a blog to the system
      public boolean insertBlog(Blog blog);
     //define the method to read a blog from the system according the id
          public Blog readBlog(Long blogId);
}

      Then, make an implementation to this interface:

//Data access object 
public class BlogDAOImpl implements BlogDAO{
      public boolean insertBlog(Blog blog){
             Session session = HibernateUtil.getSession();
             ….
      }
     public Blog readBlog(Long blogId){
             Session session = HibernateUtil.getSession();
             …. 
      }
}

//HibernateUtil is a help class
public class HibernateUtil{
        private static SessionFactory sessionFactory;
        static{
                sessionFactory = ….;
         }
        public static Session getSession(){
               return sessionFactory.openSession();
        }
}

      Now, we can create a class for testing:
public class Test{
     public static void main(String[] args){
             //insert a blog to the database
            //assume that we already get an instance of Blog class named blog

            BlogDAO blogDAO = DAOFactory.getInstance().getBlogDAO();
            blogDAO.inserBlog(blog);
     }
}

      However, there are still some drawbacks of DAO pattern. For example, we always have to get an instance of Session at the beginning of each method of the class BlogDAOImpl, which make us write the same code. Fortunately, we can make some advances to this program, for instance, we can adopt spring framework for configuring the relationship between each class.

10_11_1_3.jpeg

Blog at WordPress.com.