实现声明性事务的问题

imr*_*ran 6 grails transactions declarative

我想在功能级别实现事务控制.我想要的是这样的.

class MyService {

static transactional = false

@Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW)

public def saveCountry(){Country co = new Country(name:'mycountry')co.save()createState()

}

@Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW)

public def createState(){State state = new State(name:'state')state.save()throw new RuntimeException()}}

我想要的是createState()创建一个独立于saveCountry()的新事务,这样如果createState()失败,

已保存的国家/地区对象未被撤销.虽然我已经给出了注释,但它们没有产生预期的效果.此处创建单个事务,并在抛出异常时撤消该事务.保存对象的任何一个.

任何人都可以帮忙

小智 1

我不建议采取这种方法。当您到达 createState() 方法时,grails 将在创建新事务之前尝试使用任何打开的事务(如果没有可用的事务)。

相反,我只使用仅围绕必要的 grails 代码的小事务块,而不是尝试声明事务方法

http://www.grails.org/doc/1.3.x/ref/Domain%20Classes/withTransaction.html

例如我可以在任何地方有一个块,例如

State.withTransaction { status -> 
   //all the code in here has an explicit transaction   
}
Run Code Online (Sandbox Code Playgroud)

该事务在块末尾刷新或回滚,并且该事务具有对 Spring 对象 TransactionStatus 的引用。这使您可以对错误处理进行精细控制。这将允许您拥有大型交易块,但仍可以决定交易何时何地结束。

我会将代码更改为

public def saveCountry() {
    Country.withTransaction { status ->
        Country co = new Country(name:'mycountry')
        co.save()
    }
    createState()
}

public def createState(){
    State.withTransaction { status ->
        State state = new State(name:'state')
        state.save()
        throw new Exception
    }  
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,国家将被拯救,但国家的交易将被回滚