Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

transactions - Grails - Saving multiple object, Rollback all object if one fails to save

I need to save multiple object at once, and rollback all if one object fails to save. For example :

class Transaction {
  Item item;
}

class Item {
  date lastTransaction;
}

If I create new Transaction, I need to change lastTransaction value and save the item.
If I failed to save the item, I need to rollback the Transaction (vice versa).

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yuck. Don't throw exceptions to roll back transactions. You're incurring a pretty high cost to take advantage of a side effect where the transaction manager, assuming that a runtime exception means that you're not in control, automatically rolls back the transaction for you to keep you from doing more damage. It's a bit like being lonely and hitting yourself in the head repeatedly with a hammer so some EMTs and perhaps a nurse or a doctor will spend some time with you.

It's pretty easy to roll back a transaction, but unfortunately Grails doesn't expose any of this:

import org.springframework.transaction.interceptor.TransactionAspectSupport

class FooService {

   def someMethod(...) {

      boolean somethingBadHappened = ...
      if (somethingBadHappened) {
         // roll back
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
      }

      // ok, proceed
      ...
   }
}

And later you can check if the current transaction was rolled back with

TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()

Note that this won't work in a controller since the transaction will have ended by that point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...