gpt4 book ai didi

java - 我的 grails 项目面临错误“TransactionRequiredException :no transaction"using domain. save(flush :true). save()) 它可以保存但正在更新

转载 作者:行者123 更新时间:2023-12-02 01:11:43 27 4
gpt4 key购买 nike

package com.fhjony.ocbt


import grails.web.servlet.mvc.GrailsParameterMap


class MemberService {

def save(GrailsParameterMap params) {
Member member = new Member(params)
def response = AppUtil.saveResponse(false, member)
if (member.validate()) {
member.save(true)
if (!member.hasErrors()){
response.isSuccess = true
}
}
return response
}


def update(Member member, GrailsParameterMap params) {

member.properties = params
def response = AppUtil.saveResponse(false, member)
if (member.validate()) {
member.save(flush: true)
if (!member.hasErrors()){
response.isSuccess = true
}
}
return response
}


def getById(Serializable id) {
return Member.get(id)
}


def list(GrailsParameterMap params) {
params.max = params.max ?: GlobalConfig.itemPerPage()
List<Member> memberList = Member.createCriteria().list(params) {
if (params?.colName && params?.colValue) {
like(params.colName, "%" + params.colValue + "%")
}
if (!params.sort) {
order("id", "desc")
}
}
return [list: memberList, count: memberList.totalCount]
}


def delete(Member member) {
try {

member.delete(flush: true,failOnError:true)
} catch (Exception e) {
println(e.getMessage())
return false
}
return true
}
}

错误消息:

URI /member/update Class
javax.persistence.TransactionRequiredException Message null Caused by
no transaction is in progress
Line | Method
->> 211 | invoke in org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 188 | invoke in org.grails.core.DefaultGrailsControllerClass | 90 | handle . . . .
. in org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter | 1039
| doDispatch in
org.springframework.web.servlet.DispatcherServlet | 942 | doService
. . . in '' | 1005 | processRequest in
org.springframework.web.servlet.FrameworkServlet | 908 | doPost . .
. . . in '' | 882 | service in '' | 77 |
doFilterInternal in

最佳答案

您希望数据库交互发生在事务上下文中。其中一个简单的部分是您可以使用 @grails.gorm.transactions.Transactional 标记您的服务类。

除此之外,这与您的问题并不真正相关,但是将 GrailsParameterMap 映射作为方法参数传递是一件不寻常的事情。正确的做法取决于应用程序中的某些因素,您可能希望将值传递到服务中而不是整个 map 中,但如果您确实想要服务中的整个 map ,实现这一点的一种方法是通过WebAttributes

import grails.gorm.transactions.Transactional
import grails.web.api.WebAttributes

@Transactional
class MemberService implements WebAttributes {

def serviceMethod() {
// you can access params here because
// WebAttributes provides access to it
Member member = new Member(params)

// ...
}
}

关于java - 我的 grails 项目面临错误“TransactionRequiredException :no transaction"using domain. save(flush :true). save()) 它可以保存但正在更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57682313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com