Spring事务(四)
2020-12-28 04:29
标签:引入 lse zab 了解 优化 隔离 path mon mysql Spring事务(四) 标签:引入 lse zab 了解 优化 隔离 path mon mysql 原文地址:https://www.cnblogs.com/binwenhome/p/12997199.html事务管理概述
注解配置事务
@Repository
public class BookDAOImpl implements BookDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer selectPrice(String bid) {
Integer price = jdbcTemplate.queryForObject("select price from book where bid = ?", new Object[]{bid}, Integer.class);
return price;
}
@Override
public void updateSt(String bid) {
//先获取该书库存
Integer st = jdbcTemplate.queryForObject("select st from stock where sid = ?", new Object[]{bid}, Integer.class);
if(st ) {
throw new RuntimeException();
} else {
st--;
jdbcTemplate.update("update stock set st = ? where sid = ?", st, bid);
}
}
@Override
public void updateBalance(String uid, Integer price) {
Integer balance = jdbcTemplate.queryForObject("select balance from money where bid = ?", new Object[]{uid}, Integer.class);
if(balance price) {
throw new RuntimeException();
} else {
jdbcTemplate.update("update money set balance = balance - ? where uid = ?", price, uid);
}
}
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDAO dao;
@Override
public void buyBook(String bid, String uid) {
Integer price = dao.selectPrice(bid);
dao.updateSt(bid);
dao.updateBalance(uid, price);
}
}
@Controller
public class BookController {
@Autowired
private BookService service;
public void buyBook() {
service.buyBook("1", "1001");
}
}
public static void main(String[] args) {
ConfigurableApplicationContext cac = new ClassPathXmlApplicationContext("book.xml");
BookController controller = cac.getBean("bookController", BookController.class);
controller.buyBook();
cac.close();
}
context:property-placeholder location="classpath:conf/db.properties" />
bean id="data" class="com.alibaba.druid.pool.DruidDataSource">
property name="driverClassName" value="${jdbc.driver}">property>
property name="url" value="${jdbc.url}">property>
property name="username" value="${jdbc.username}">property>
property name="password" value="${jdbc.password}">property>
bean>
bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
property name="dataSource" ref="data">property>
bean>
tx:annotation-driven transaction-manager="dataSourceTransactionManager" />
@Override
@Transactional
public void buyBook(String bid, String uid) {
Integer price = dao.selectPrice(bid);
dao.updateSt(bid);
dao.updateBalance(uid, price);
}
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ,
timeout = 3, readOnly = true, noRollbackFor = {NullPointerException.class, ArithmeticException.class})