基于XML的声明式事务

场景模拟

参考基于注解的声明式事务

修改Spring的配置文件

将Spring配置文件中去掉tx:annotation-driven标签,并添加配置:





    


        
        
            
            
            
            
        


    
        
    


    
        
    


    
        
            
            
            
        
    


    
        
        
    

Controller

@Controller
public class BookController {

    @Autowired
    private BookService bookService;
    /**
     * 买书的方法
     * @param bookId
     * @param userId
     */
    public void buyBook(Integer bookId,Integer userId){
        //调用Service方法
        bookService.buyBook(bookId,userId);
    }

}

 Service

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    /**
     * 买书的方法
     * @param bookId
     * @param userId
     */
    @Override
    public void buyBook(Integer bookId, Integer userId) {

        //根据图书id查询图书价格
        Integer price = bookDao.getBookPriceByBookId(bookId);

        //更新图书库存量 -1
        bookDao.updateStock(bookId);

        //更新用户表用户余额 -图书价格
        bookDao.updateUserBalance(userId,price);


    }
}

Dao

@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据id查询图书价格
     * @param bookId
     * @return
     */
    @Override
    public Integer getBookPriceByBookId(Integer bookId) {
        String sql = "select price from t_book where book_id = ?";
        Integer price = jdbcTemplate.queryForObject(sql, Integer.class, bookId);
        return price;
    }

    /**
     * 更新库存信息
     * @param bookId
     */
    @Override
    public void updateStock(Integer bookId) {
        String sql = "update t_book set stock = stock -1 where book_id = ?";
        jdbcTemplate.update(sql,bookId);

    }

    /**
     * 更新用户表用户余额 -图书价格
     * @param userId
     * @param price
     */
    @Override
    public void updateUserBalance(Integer userId, Integer price) {
        String sql = "update t_user set balance = balance - ? where user_id = ?";
        jdbcTemplate.update(sql,price,userId);

    }
}

 测试:

@SpringJUnitConfig(locations = "classpath:beans-xml.xml")
public class TestBookTx {

    @Autowired
    private BookController bookController;

    @Test
    public void testBuyBook(){
        bookController.buyBook(1,1);

    }

}

某些小细节:

基于XML的声明式事务_第1张图片

基于XML的声明式事务_第2张图片

你可能感兴趣的:(xml,java,数据库)