mysql - 如何使事务在 Grails 中工作

标签 mysql hibernate grails transactions grails-orm

总结 一个 parent 可以有很多 child 。你如何编写一个服务,如果在添加父项后添加子项时出错,则回滚整个事务。比如添加parent p1,成功添加child c1,然后添加child c2时出错,p1和c1都要回滚。

详细问题

在下面的代码中,对子项的名称属性进行了唯一约束。因此,如果您尝试使用不同的父记录两次添加相同的名称,则不应添加子记录并且应回滚父记录。

我的问题是父记录没有被回滚。

我正在使用带有 InnoDB 的 MySQL 以及 Grails 1.2-M2 和 Tomcat 6.018。

数据源

import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration
dataSource {
    configClass = GrailsAnnotationConfiguration.class
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = org.hibernate.dialect.MySQLInnoDBDialect
    zeroDateTimeBehavior="convertToNull" //Java can't convert ''0000-00-00 00:00:00' to TIMESTAMP
    username = "root"
    password = "12345"
    loggingSql=false
}

hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='com.opensymphony.oscache.hibernate.OSCacheProvider'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop','update'
                url = "jdbc:mysql://localhost:3306/transtest?zeroDateTimeBehavior=convertToNull"

        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost:3306/transtest?zeroDateTimeBehavior=convertToNull"

        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost:3306/transtest?zeroDateTimeBehavior=convertToNull"
        }
    }
}

我有以下简单的域类:

家长:

class Parent {

    static hasMany = [ children : Child ]

    String  name

    static constraints = {
        name(blank:false,unique:true)
    }
}

child

class Child {

    static belongsTo = Parent

    String name

    Parent parent

    static constraints = {
        name(blank:false,unique:true)
    }
}

简单数据输入 GSP

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Sample title</title>
  </head>
  <body>
    <h1>Add A Record</h1>
  <g:form action="add" name="doAdd">
    <table>
      <tr>
        <td>
          Parent Name
        </td>
        <td>
          Child Name
        </td>
      </tr>
      <tr>
        <td>
          <g:textField name="parentName"  />
        </td>
        <td>
          <g:textField name="childName" />
        </td>
      </tr>
      <tr><td><g:submitButton name="update" value="Update" /></td></tr>
    </table>
  </g:form>
</body>
</html>

Controller

class AddrecordController {

    def addRecordsService

    def index = {
        redirect action:"show", params:params
    }

    def add = {
        println "do add"


        addRecordsService.addAll(params)
        redirect action:"show", params:params

    }

    def show = {}

}

服务

class AddRecordsService {

   // boolean transactional = true //shouldn't this be all I need?
      static transactional = true // this should work but still doesn't nor does it work if the line is left out completely
    def addAll(params) {
        println "add all"
        println params
        def Parent theParent =  addParent(params.parentName)
        def Child theChild  = addChild(params.childName,theParent)
        println theParent
        println theChild
    }

    def addParent(pName) {
        println "add parent: ${pName}"
        def theParent = new Parent(name:pName)
        theParent.save()
        return theParent
    }

    def addChild(cName,Parent theParent) {
        println "add child: ${cName}"
        def theChild = new Child(name:cName,parent:theParent)
        theChild.save()
        return theChild
    }

}

最佳答案

您还需要确保在服务中抛出 RuntimeException,以便自动回滚事务。

所以我会这样做:

def addParent(pName) {
        println "add parent: ${pName}"
        def theParent = new Parent(name:pName)
        if(!theParent.save()){
            throw new RuntimeException('unable to save parent')
        }
        return theParent
    }

def addChild(cName,Parent theParent) {
    println "add child: ${cName}"
    def theChild = new Child(name:cName,parent:theParent)
    theChild.save()
    if(!child.save()){
        throw new RuntimeException('unable to save child')
    }
    return theChild
}

然后在 Controller 中捕获异常并呈现错误。

另一种方法是关闭自动事务并使用 Parent.withTransaction 如果存在验证错误,则手动将事务标记为回滚。

关于mysql - 如何使事务在 Grails 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1628982/

相关文章:

grails - 与Grails的零对多关系?

php - 如何防止 PHP 中的 SQL 注入(inject)?

java - 跨越多个存储库的 Spring Data Transaction

tomcat - 在运行时在 Grails 应用程序中修改 groovy 代码

mysql - Hibernate CURRENT_TIMESTAMP 和 MySQL 中的多实体事务

java - hibernate - 如何 JoinColumn 一个 EmbeddedId

grails - GSP 页面中的递归

php - 在 MySQL 中使用 `LIKE` 和 `MATCH AGAINST` 搜索数据库

php - 无法使用api将数据插入android中的数据库

php - 如何使用 php 在 Joomla 数据库中设置限制?