http://www.cnblogs.com/wyqtomorrow/archive/2007/05/28/762425.html[@more@]
编程式的事务管理:我们可以使用 org.springframework.jdbc.datasource.DataSourceTransactionManager(platformTransactionManager 的一个实现)作为我们的事务管理员,我们在Bean定义中配置,并将DataSource注入给它。
配置文件:
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
span class="code-quote">"-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
"dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
"driverClassName">
com.mysql.jdbc.Driver"url">
jdbc:mysql://localhost:3306/TestDB"username">
root"password">
"transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
"dataSource">
"dataSource"/>
"userDAO" class="onlyfun.caterpillar.UserDAO">
"dataSource">
"dataSource"/>
"transactionManager">
"transactionManager"/>
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);
} }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25261409/viewspace-1058328/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/25261409/viewspace-1058328/