mikek
mikek

Reputation: 169

Grails - Managing database transactions with rollbacks

GGTS 3.4 Grails 2.3.3 - When generating controllers this version includes a number of @Transactional lines I haven't seen before, and I don't fully understand what they are doing.

At the top of the controller there is the line:

@Transactional(readOnly = true)

Then just before certain dB changing actions: 'save', 'update' and 'delete' there is the line:

@Transactional

I presume that this switches the readOnly to false for each dB changing action. Does it open a new transaction that can be committed or rolled back as well? Is there simple way to force a rollback?

The 'create' action does not have @Transactional line before it despite it carrying out a 'new' db command to create a new instance of the specific domain class. What happens to this newly created but unsaved instance if the save transaction is not completed or if it is rolled back? By not completed I am thinking of introducing a 'cancel' button in the 'create' view to enable users to pull out of the creation if they choose to - also a user could simply navigate out of the create view without invoking the save.

-mike

Upvotes: 0

Views: 344

Answers (2)

Piyush Chaudhari
Piyush Chaudhari

Reputation: 1012

You can you use "withTransaction" method of domains to manage your Transaction manually as follow:

Account.withTransaction { status ->

try{ write your code or business logic here }catch(Exception e){

  status.setRollbackOnly()

} }

if exception generate then this Transaction will be rollback

Upvotes: 0

Joshua Moore
Joshua Moore

Reputation: 24776

The standard @Transactional without any properties set uses the platform defaults. These depend upon your transaction manager and your data source. It does however, create a transaction that can be comitted or rolled back.

Conroller methods without any annotation do not particpate in any transactions (provided the entire class isn't annotated as well).

In the case of create there is no need for a transaction because you aren't interacting with the database/transaction manager. Simply creating a new instance of a domain class e.g. new MyDomainClass() doesn't interact with the database at all, which is what you are seeing in the create method.

So in short, you don't need to worry about that instance if your users navigate away from the page or click cancel.

Upvotes: 0

Related Questions