Search code examples
javahibernateormh2embedded-database

slow embedded database processing with hibernate


I use h2 database in embedded mode, also I use hibernate to access it. That is my spring config I am using to initialize hibernate:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

    <property name="dataSource">
        <ref bean="dataSource" />
    </property>

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>

    <property name="annotatedClasses">
        <list>
            <value>classname1</value>
            <value>classname2</value>
            <value>classname3</value>
        </list>
    </property>
</bean>

when I try insert data database works very, very slow and I have very huge IO stream (as fast as hard drive is able). I think database is opened and closed every time when

getHibernateTemplate().save(question);
is called. What is interesting, if I change connection string to use standalone server this problem disappears and all works nice.

What is wrong with my config for embedded databases?

UPD

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.jdbcx.JdbcDataSource" />
    <property name="url" value="jdbc:h2:file:C:\temp\data.db" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

Solution

  • The implementation org.springframework.jdbc.datasource.DriverManagerDataSource opens and closes a connection whenever you request one.

    From the JavaDoc:

    NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.

    For production environments it's highly recommended that you use a connection pool which opens a limited number of connections up-front and pools them for usage. For your dataSource I'd say use Apache's Jakarta Commons DBCP or C3P0. This example shows how you can set up your dataSource to use DBCP. Using a connection pool will definitely reduce the time spend to query the database and will most certainly solve your problem.