日期:2014-05-16  浏览次数:20492 次

直接使用groovy的sql来直接进行DB操作
特殊的需求,在GRAILS调用GROOVY SQL直接做数据更新、插入和删除,如何控制原子事务?



比较特殊的处理方案(如果有更好的方案,还请赐教)。

场景:SQL是用DATASOURCE创建的。

描述:因为设置是否自动提交是由CONNECTION处理的,但是直接用dataSource来创建,是没法得到connection的引用,所以必须用如下方式:



        def dbTran  = new groovy.sql.Sql(dataSource)
        def con = dbTran.createConnection()
        def db =  new groovy.sql.Sql(con)

        try{

            con.autoCommit = false

            db.execute("delete from rcbinfo")

            db.insert.........

            con.commit()

        }catch(Exception e){

            con.rollback()

        }finally{

            con.autoCommit = true

        }








import groovy.sql.Sql

class MyFancySqlController {

    def dataSource // the Spring-Bean "dataSource" is auto-injected

    def list = {
        def db = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app

        def result = db.rows("SELECT foo, bar FROM my_view") // Perform the query

        [ result: result ] // return the results as model
    }

}