我正在使用 Spring 的 @Transactional 和 Hibernate。我正在尝试将两个 dao 方法放入一个事务中,并希望回滚特定的异常。代码如下:
服务类方法:
@Transactional(propagation=Propagation.REQUIRES_NEW,value="txManager",rollbackFor=TransactionUnSuccessException.class)
public Account makeTransaction(Transaction transaction, String userName)
throws TransactionUnSuccessException {
Account account = null;
account = transferDao.makeTransaction(transaction, userName);
return account;
}
道法:
@Repository
public class TransferDao extends HibernateDaoSupport {
@Autowired
private SessionFactory sessionFactory;
public Account makeTransaction(Transaction transaction, String userName)
throws TransactionUnSuccessException {
HibernateTemplate hibernateTemplate = getHibernateTemplate();
Account account = null;
Session session = hibernateTemplate.getSessionFactory().openSession();
//session.beginTransaction();
updateSelfAccount(transaction, userName, session);
account = updateAnotherAcccount(transaction, session);
//session.getTransaction().commit();
return account;
}
private void updateSelfAccount(Transaction transaction, String userName,
Session session) {
User currentUser = null;
System.out.println("TransferDao.updateSelfAccount()" + transaction);
Query query = session.createQuery("from User where userName=:userName");
query.setParameter("userName", userName);
currentUser = (User) query.list().get(0);
currentUser.getAccount().getTransactions().add(transaction);
currentUser.getAccount().setAvailableBalance(
currentUser.getAccount().getAvailableBalance()
- transaction.getAmount());
transaction.setTransAccount(currentUser.getAccount());
session.save(transaction);
session.update(currentUser.getAccount());
session.update(currentUser);
private Account updateAnotherAcccount(Transaction transaction,
Session session) throws TransactionUnSuccessException {
Account account = null;
try {
Query query = session
.createQuery("from Account where accNo=:accNo");
query.setParameter("accNo", transaction.getToAcc());
account = (Account) query.list().get(0);
if (account.getAvailableBalance() < 5000) {
account.setAvailableBalance(account.getAvailableBalance()
+ transaction.getAmount());
account.getTransactions().add(transaction);
transaction.setTransAccount(account);
session.save(transaction);
session.update(account);
} else {
throw new TransactionUnSuccessException();
}
} catch (TransactionUnSuccessException te) {
te.printStackTrace();
}
return account;
}
}
}
xml配置:
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
如果这两种方法(updateSelfAccount,updateAnotherAccount)中的任何一种失败,则整个事务应该回滚。但是即使我不确定这一切都发生在单个事务中,它也无法回滚给定的异常。请纠正我。