Declarative transactions in Spring

By Shahram Javey

Spring applicationContext.xml file for the sample projectSpring declarative transactions, and the DAO design pattern simplify database (& JMS) programming. With the DAO design pattern, you need to create your domain objects and encapsulate the database access in the DAO classes. This makes up the model part of your application. The model component also includes the business (aka manager layer) that captures the semantics of your application. The methods of the business layer need to be enlisted in the transaction. I’ve updated my sample project to include the business layer and a JUNIT test case for the transaction. Here is test method:


	public void testTransaction() {
		int countBefore = workManager.getAllParents().size();
		Parent p = new Parent();
		p.setName("Big Daddy");
		Child c = new Child();
		c.setName("Johnny");
		p.addChild(c);
		try {
			workManager.saveParentAndThrowException(p);
			fail("Should have thrown RuntimeException");
		} catch (Exception x) {
			assertTrue(x instanceof RuntimeException);
		}
		int countAfter = workManager.getAllParents().size();
		assertTrue("The new parent should not have been added", countBefore==countAfter);
	}

With Spring’s declarative transaction, I didn’t have to programmatically access the transaction or in case of failure manage the rollback. With this approach you just write your methods as you would normally do in a non-transactional system, and then just throw an exception if something goes wrong. When the exception is thrown, the transaction is rolled back.

For each of the manager classes in the business layer, you’ll need to configure Spring to use the the TransactionProxyFactoryBean for your manager class, e.g., in this sample project, here is the Spring configuration:



    <bean id="workManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager"><ref bean="transactionManager"/></property>
        <property name="proxyTargetClass"><value>true</value></property>
        <property name="target"><ref local="workManagerTarget"/></property>
        <property name="transactionAttributes">
            <props>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
            </props>
        </property>
    </bean>

    <bean id="workManagerTarget" class="com.acme.business.DefaultWorkManager">
        <property name="parentDao"><ref local="parentDao"/></property>
    </bean>

One Response to “Declarative transactions in Spring”

  1. sj Says:

    See also cascaded deletes and lazy initialization entries.

Leave a Reply