What Spring allows you to do, thanks to AOP, use declarative transactions, as you could do with EJB.
Instead of doing
public void doSomething() { Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work ... tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; // or display error message } finally { sess.close(); } }
You just do
@Transactional public void doSomething() {
Which is much more readable, more convenient, less bulky, and safer since Spring handles transactional logic for you. To do this, you need a transaction manager: tell Spring how it should handle transactions for you. Because it can also use the same declarative model, but use JPA transactions or JTA transactions.
This is well described in the Spring documentation.
source share