使用spring的annotation配置事务
首先配置Hibernate的局部事务管理,使用HibernateTransactionManager类,该类实现了PlatformTransactionManager接口,是针对Hibernate的特定实现,如下添加:
<bean id="transactionManager" ref="sessionFactory"></property> </bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<?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>
@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);}}