Spring的事务管理器接口:
Spring提供的实现
这里是单数据源,可以使用DataSourceTransactionManager:
FruitShop实现类:
beans-fruitshop.xml文件:
测试:
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; // 获取事务状态 void commit(TransactionStatus status) throws TransactionException; // 提交事务 void rollback(TransactionStatus status) throws TransactionException; // 回滚事务 }
Spring提供的实现
这里是单数据源,可以使用DataSourceTransactionManager:
FruitShop实现类:
public class TransactionalApiJdbcFruitShop extends JdbcDaoSupport implements FruitShop { private PlatformTransactionManager txManager; public void setTxManager(PlatformTransactionManager txManager) { this.txManager = txManager; } @Override public boolean purchase(int fruitId, String userName, int count) { TransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus status = txManager.getTransaction(definition); String querySql = "SELECT PRICE FROM FRUIT WHERE ID = ?"; String upStockSql = "UPDATE FRUIT_STOCK SET STOCK = STOCK - ? WHERE ID = ?"; String upAccountSql = "UPDATE ACCOUNT SET BALANCE = BALANCE - ? WHERE USERNAME = ?"; try { int price = getJdbcTemplate().queryForInt(querySql, new Object[] { fruitId }); getJdbcTemplate().update(upStockSql, new Object[] { count, fruitId }); getJdbcTemplate().update(upAccountSql, new Object[] { price * count, userName }); txManager.commit(status); } catch (DataAccessException e) { txManager.rollback(status); throw e; } catch (TransactionException e) { txManager.rollback(status); throw e; } return true; } }
beans-fruitshop.xml文件:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/spring?characterEncoding=utf8" /> <property name="username" value="spring" /> <property name="password" value="123456" /> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="txApiFruitShop" class="com.john.tx.service.impl.TransactionalApiJdbcFruitShop"> <property name="dataSource" ref="dataSource" /><!--JdbcDaoSupport的子类需要指定dataSource--> <property name="txManager" ref="txManager" /> </bean>
测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/beans-fruitshop.xml" }) public class JdbcFruitShopTest { @Resource(name = "txApiFruitShop") FruitShop txApiFruitShop; @Test public void txApiTest() { int fruitId = 1; String userName = "user1"; int count = 3; txApiFruitShop.purchase(fruitId, userName, count); } }