Spring学习笔记(八)-----事务管理(编程式事务管理)

编程式的事务管理:我们可以使用org.springframework.jdbc.datasource.DataSourceTransactionManager(platformTransactionManager的一个实现)作为我们的事务管理员,我们在Bean定义中配置,并将DataSource注入给它。
配置文件:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName">

<value>com.mysql.jdbc.Driver</value>

</property>

<property name="url">

<value>jdbc:mysql://localhost:3306/TestDB</value>

        </property>

<property name="username">

<value>root</value>

</property>

<property name="password">

<value></value>

</property>

</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource">

<ref bean="dataSource"/>

</property>

</bean>

<bean id="userDAO" class="onlyfun.caterpillar.UserDAO">

<property name="dataSource">

<ref bean="dataSource"/>

</property>

<property name="transactionManager">

<ref bean="transactionManager"/>

</property>

</bean>

</beans>
DAO操作类:

package onlyfun.caterpillar;

import javax.sql.DataSource;

import org.springframework.jdbc.core.*;

import org.springframework.transaction.*;

import org.springframework.transaction.support.*;

import org.springframework.dao.*;

public class UserDAO {

private DataSource dataSource;

private PlatformTransactionManager transactionManager;

public void setDataSource(DataSource dataSource) {

this.dataSource = dataSource;

}

public void setTransactionManager(PlatformTransactionManager transactionManager) {

this.transactionManager = transactionManager;

}

public void insertUser(User user) {

DefaultTransactionDefinition def = new DefaultTransactionDefinition();

TransactionStatus status = transactionManager.getTransaction(def);

try {

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

jdbcTemplate.update("INSERT INTO USER VALUES('Spring008', 'caterpillar', 'M', 29)");

jdbcTemplate.update("INSERT INTO USER VALUES('Spring009', 'momor', 'F', 26)");

jdbcTemplate.update("INSERT INTO USER VALUES('Spring010, 'beckyday', 'F', 35)");

} catch (DataAccessException ex) {

transactionManager.rollback(status); // 也可以執行status.setRollbackOnly();

        throw ex;

}

transactionManager.commit(status);
} }

你可能感兴趣的:(spring)