Monday, December 28, 2015

Spring - Declarative transaction management

To use the Xml based Spring Transaction management all you have to do is to add 3 simple bean configuration in your xml file i.e: 

  1. Initializing DataSourceTransactionManager bean
  2. <tx:advice />: Configures the transaction advice. In this advice we configure various transaction properties for different methods. So what was earlier written as@Transactional(readOnly = true) will now be written as <tx:method name="select*" read-only="true" />.
  3. <aop:config/>: Final step is to apply the transaction advice using aop configuration.

<context:annotation-config/>

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:methodname="select*" read-only="true"/>
<tx:methodname="*"/>
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id="userDaoTxPointcut" expression="execution(* spring jdbc.IUserDao.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="userDaoTxPointcut"/>
</aop:config>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/apu"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource "ref="dataSource"></property>
</bean>

<bean id="userDao" class="springjdbc.transactions.declarative.xml.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

No comments:

Post a Comment