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?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits: Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).
Hibernate is for ORM ( object relational mapping ) that is, make your objects persistent to a RDBMS. Spring goes further. It may be used also as a AOP, Dependency Injector, a Web Application and ORM among other things. So if you only need ORM, just use Hibernate.
So when you annotate a method with @Transactional , Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
The difference between Spring and Hibernate is that spring is a complete and a modular framework for developing Enterprise Applications in Java while Hibernate is an Object Relational Mapping framework specialized in data persisting and retrieving from a database. Hibernate is integrated into to Spring framework.
The real advantages are:
Lightweight declarative syntax. Compare:
public void saveEmployee(Employee e) {
Session s = sf.getCurrentSession();
s.getTransaction().begin();
s.save(e);
s.getTransaction().commit();
}
and
@Transactional
public void saveEmployee(Employee e) {
sf.getCurrentSession().save(e);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With