首页 > 数字化转型 > ERP > jdbctemplate事务管理
"1.0" encoding="UTF-8"?> "-//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博客 ” ,链接:https://blog.itpub.net/25261409/viewspace-1058328/ ,如需转载,请注明出处,否则将追究法律责任。