views:

53

answers:

1

Hi guys, what is the difference between use @Transactional over a method and not use it?

I write some simple test but seem to be no difference.

I want to learn how to manage transaction using spring and annotation.

thank all.

+1  A: 

If you put @Transactional over a method, every method call inside that accesses database (but also every method call inside the other @Transactional methods - depends how you set it up) uses only one database Connection. It means, that you can rollback all the updates/inserts that happened within the transaction. If one of the updates/inserts throws an Exception, you can rollback all the updates/inserts within transaction that happened before that exception -> data integrity

Simply put, if you have a @Transactional method which for instance uses spring JdbcTemplate to do some inserts or updates (no matter how many times), they will be transactional, in terms of if some exception is thrown or something, rollback is applied - you must read the documentation on details.

if you use @Transactional(propagation = Propagation.REQUIRED) on more then one method, if you then call these methods, all the inserts/updates into database withing these methods will be part of one big transaction.

IMPORTANT: as I mentioned in the comment, you must not call these method from the same class where they are declared. The reason is, that it is all based on AOP proxy calls which happens only if you instantiate the DAO object and invoke the @Transactional methods on the object. Otherwise it won't work and you wouldn't probably figure out why.

lisak
@lisak: Can i think to @Transactional like a session.beginTransaction() -> myTransactionalMtehod() -> transaction.commit()? If i call two consecutive method that using @transactional, transaction are begin tiwce?
blow
You can think of it like that, but in a distributed way. If you choose the option "PROPAGATION_REQUIRED", then all the @Transactional methods are part of one big transaction...the transaction then may cover persistence methods from various places. It's an AOP where before the persistence method is doing DB requests, it is supplied with shared database Connection, so that all the methods that are part of the transaction, requests DB from the same object, then it is possible to commit / rollback. It is important to know that you must call the @Transactional methods from different class/object.
lisak
It's an AOP proxy, so that you can't call the @Transactional methods from the same object, the call wouldn't be proxied and there wouldn't be any transactions...just instantiate the DAO object, having @Transactional methods, somewhere else and call the methods on it...
lisak