问题描述
我一直在努力学习spring和hibernate,并且我已经在网络上使用了很多示例来组合一个很好的应用程序。不过,我现在意识到Spring支持事务管理。在我的春季应用程序中,我只是简单地拨打我想要的任何电话,直接进入休眠状态。是否有理由/利益为什么人们会使用Spring的事务管理/数据库的东西?
I've been trying to learn spring and hibernate, and I've used a lot of examples around the net to put together a nice application. However, I realized now that Spring supports transaction management. In my spring app I just simply made whatever calls I wanted to, directly to hibernate. Is there a reason/benefit as to why people would use Spring's transaction management/db stuff?
推荐答案
真正的优点是:
-
轻量级声明式语法。比较:
Lightweight declarative syntax. Compare:
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,事务传播平稳运行:
Flexible transaction propagation. Imagine that now you need to execute this saveEmployee()
method as a part of a complex transaction. With manual transaction management, you need to change the method since transaction management is hard-coded. With Spring, transaction propagation works smoothly:
@Transactional
public void hireEmployee(Employee e) {
dao.saveEmployee(e);
doOtherStuffInTheSameTransaction(e);
}
例外时自动回滚
Automatic rollback in the case of exceptions
这篇关于使用Spring事务管理与使用Hibernate的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!