真正的优点是:
- 轻量级声明性语法。相比:
public void saveEmployee(Employee e) { Session s = sf.getCurrentSession(); s.getTransaction().begin(); s.save(e); s.getTransaction().commit(); }和
@Transactional public void saveEmployee(Employee e) { sf.getCurrentSession().save(e); }- 灵活的交易传播。想象一下,现在您需要在
saveEmployee()
复杂事务中执行此方法。对于手动事务管理,由于事务管理是硬编码的,因此您需要更改方法。使用Spring,事务传播可以顺利进行:
@Transactional public void hireEmployee(Employee e) { dao.saveEmployee(e); doOtherStuffInTheSameTransaction(e); }- 发生异常时自动回滚



