使用spring的annotation配置事务
首先配置Hibernate的局部事务管理,使用HibernateTransactionManager类,该类实现了PlatformTransactionManager接口,是针对Hibernate的特定实现,如下添加:
<bean id="transactionManager" ref="sessionFactory"></property> </bean>
另外需要开启annotation支持,添加如下配置:
<tx:annotation-driven transaction-manager="transactionManager"/>
添加完成后我的applicationContext.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- derby创建用户名和密码参考:http://www.joyzhong.com/archives/643 --> <bean id="dataSource" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/></beans>
使用事务时,只需要在某方法上使用@Transactional标注即可,例如:
@Service("accountService")public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Autowiredprivate BookDao bookDao;public AccountDao getAccountDao() {return accountDao;}public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public BookDao getBookDao() {return bookDao;}public void setBookDao(BookDao bookDao) {this.bookDao = bookDao;}@Overridepublic Account getAccountByUserID(int user_id) {Account account = this.accountDao.getAccountByUserID(user_id);return account;}@Transactional@Overridepublic void buyBooks(Account account, Book book, int num) {account.setBalance(account.getBalance() - book.getPrice()*num);book.setAmount(book.getAmount() - num);this.bookDao.update(book);this.accountDao.update(account);}}
上面的buyBooks模拟了一次购买书的过程,在这次购书过程中需要两次与数据库交互,首先调用bookDao的update方法减少书的数量,然后调用accountDao的update方法减少账户余额。如果该过程不采用事务,假设某一次买书的过程中书的数量是充足的,而账户的余额不足,那么就会出现书的数量减少了而余额却仍是原来的余额,这肯定出问题。加上事务之后就不会出现了上面的问题了,如果这次执行中出现了异常,那么事务的全部操作都被回滚。