日期:2014-05-16 浏览次数:20419 次
try { ..... connection.setAutoCommit(false); ..... // 一连串SQL操作 connection.commit(); } catch(SQLException) { // 发生错误,撤消所有变更 connection.rollback(); }
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; }
public interface TransactionStatus { boolean isNewTransaction(); void setRollbackOnly(); boolean isRollbackOnly(); }
package onlyfun.caterpillar; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc. datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction. support.DefaultTransactionDefinition; public class UserDAO implements IUserDAO { private DataSourceTransactionManager transactionManager; private DefaultTransactionDefinition def; private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); transactionManager = new DataSourceTransactionManager(dataSource); // 建立事务的定义 def = new DefaultTransactionDefinition(); def.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRED); } public void insert(User user) { String name = user.getName(); int age = user.getAge().intValue(); TransactionStatus status = transactionManager.getTransaction(def); try { jdbcTemplate.update("INSERT INTO user (name,age) " + "VALUES('" + name + "'," + age + ")"); // 下面的SQL有错误,用以测试事务 j