Hibernate Configuration

The following uses Spring + Hibernate:

    <bean id="dataSource"
        class="..."
        p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/products"
        p:username="..." p:password="..." />

The datasource class will depend on desired features:

1) org.springframework.jdbc.datasource.DriverManagerDataSource
2) com.mchange.v2.c3p0.ComboPooledDataSource
3) org.apache.commons.dbcp.BasicDataSource
4) org.springframework.jdbc.datasource.SingleConnectionDataSource

Next we define Hibernate properties:

    <bean id="hibernateProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="properties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

Now the Session Factory:

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" p:hibernateProperties-ref="hibernateProperties"
        p:packagesToScan="com.example.packages">
    </bean>

Transaction support:

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory" />

    <tx:annotation-driven />

Now we can simply wire the dataSource or sessionFactory into our beans with @Autowired

We can demarcate our transction boundaries with @Transactional

Note: If using SpringJUnit4ClassRunner methods demarcated with @Transactional will not commit unless @Rollback(false) or @TransactionConfiguration(defaultRollback=false) is specified. See: http://forum.spring.io/forum/spring-projects/data/53804-commit-transactions-running-springjunit4classrunner

——–

To test our DAOs:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/session-factory.xml"})
@Transactional
public class SimpleDaoIT {

    @Autowired
    private SimpleDao dao;

    @Test
    public void test(){ ...}

}

.

Advertisements
Posted in Hibernate, Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: