Como fazer Transações Trabalho em Grails
-
06-07-2019 - |
Pergunta
Resumo Um pai pode ter muitos filhos. Como você escrever um serviço de tal forma que, se após a adição de um pai há um erro ao adicionar uma criança, toda a transação é revertida. Por exemplo, p1 add pai, adicionar com êxito c1 criança, de volta, em seguida, quando a adição de criança c2 ocorre um erro, tanto P1 e c1 deve ser rolada.
detalhada do problema
No código a seguir, há uma restrição exclusiva sobre a propriedade de nome da criança. Então, se você tentar adicionar o mesmo nome duas vezes com um pai diferente, então o registro filho não deve ser adicionado e o registro pai deve ser revertida.
Meu problema é que o registro pai não está sendo revertida.
Eu estou usando MySQL w / InnoDB com Grails 1.2 M2 e Tomcat 6.018.
Fonte de Dados
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"
}
}
}
Eu tenho as seguintes classes de domínio simples:
pai :
class Parent {
static hasMany = [ children : Child ]
String name
static constraints = {
name(blank:false,unique:true)
}
}
Criança
class Child {
static belongsTo = Parent
String name
Parent parent
static constraints = {
name(blank:false,unique:true)
}
}
simples de entrada de dados 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>
Controlador
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 = {}
}
Serviço
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
}
}
Solução
Você também precisa ter certeza de uma RuntimeException é jogado dentro do serviço, a fim de que a transação seja automaticamente revertida.
Então, eu faria isso:
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
}
e, em seguida, capturar exceções no controlador e tornar os erros.
A outra maneira é transformar de transações automáticas e uso Parent.withTransaction e marcar manualmente a transação de reversão se há um erro de validação.
Outras dicas
Eu acredito que deve ser:
class AddRecordsService {
static transactional = true;// note *static* not boolean
}
Alternativamente, você pode usar a propriedade FailOnError ao salvar seus objetos de domínio -. Se o teste falhar por um erro de validação, então ele vai lançar uma exceção
def addChild(cName,Parent theParent) {
println "add child: ${cName}"
def theChild = new Child(name:cName,parent:theParent)
theChild.save(failOnError:true)
return theChild
}
Este comportamento pode também ser habilitado globalmente, com, definindo a propriedade grails.gorm.failOnError em grails-app / conf / Config.groovy para true
Para obter mais informações, consulte o Guia do Usuário docs para 'salvar': http://grails.org/doc/latest/ref/Domain%20Classes/save.html