Senthil RS
Senthil RS

Reputation: 321

what is the difference between @Transactional and @Transactional(readOnly=true)

Can anyone tell me what is the difference between @Transactional and @Transactional(readOnly=true) in spring/hibernate.

Why we need to use @Transactional/@Transactional(readOnly=true) annotations in Service layer and not in DAO layer?

Please advise

Upvotes: 2

Views: 6540

Answers (2)

Gabe
Gabe

Reputation: 441

@Transactional vs @Transactional(readOnly=true):

The boolean readOnly is by default, which means @Transactional = @Transactional(readOnly=false), which effectively means you are hinting that the method would require write access. For a method that doesn't need data modification, you would annotate it with readOnly=true. This doesn't mean that using the annotation will automatically handle that for you, though - you will still need your entity managers, etc set up to effectively use it. Check out this page for more info.

One main reasons why we put the annotation on the Service layer and not the DAO layer, is we usually define the business logic on the service layer, and a logic may require multiple database interactions, and having it on the service layer encapsulates all the db calls will be done in one transaction (e.g. a rollback on all the db calls if it fails, etc).

Upvotes: 5

Jakub H
Jakub H

Reputation: 2158

From Spring documentation:

true if the transaction is read-only. Defaults to false.

This just serves as a hint for the actual transaction subsystem; it will not necessarily cause failure of write access attempts. A transaction manager which cannot interpret the read-only hint will not throw an exception when asked for a read-only transaction but rather silently ignore the hint.

Which means that readOnly flag if set to 'true' serves only as a hint for the transaction subsystem that your transaction will not attempt to modify any data.

@Transactional annotation is mostly used in the Service Layer, because your business methods can consist of many DAO methods calls that you might want to process in one transaction.

This question was already asked and you can read more about it here: Where should "@Transactional" be place Service Layer or DAO

Upvotes: 2

Related Questions