Hibernate “Grails错误”;违反外键约束“;尝试一次保存多个对象时无法添加对象

Hibernate “Grails错误”;违反外键约束“;尝试一次保存多个对象时无法添加对象,hibernate,grails,gorm,Hibernate,Grails,Gorm,我正在尝试保存映射为- class Order { String prefix Long orderNumber Date date Incident incident //..... few more variables } class Incident { Double amountToCharge String description Boolean isCharged = false Order order //..

我正在尝试保存映射为-

class Order {
   String prefix
   Long orderNumber
   Date date
   Incident incident
   //..... few more variables
}

class Incident {
    Double amountToCharge
    String description
    Boolean isCharged = false
    Order order
    //..... few more variables
}
现在,当我试图将它们保存在我的服务类中时,我会执行以下操作-

def save(Order orderInstance, params){
    orderInstance.withTransaction { status ->

          if (orderInstance.save()) {

            if(params.isIncident){
                def incidentStatus = saveIncident(params, orderInstance)

                if(incidentStatus.result == true){
                    println "-----------------Incident Saved"
                }else{
                    status.setRollbackOnly()
                    result["result"] = false
                    result["message"] = "Could not save. Please try again."
                    return result
                }
            }

            result["result"] = true

            return result
        } else {

            for (fieldErrors in orderInstance.errors) {
                for (error in fieldErrors.allErrors) {
                    result["message"] = messageSource.getMessage(error, locale)
                }
            }
            return result
        }
    }
}

def saveIncident(params, Order orderInstance){
    def result = [:]

    def paramsMap = [:]
    paramsMap.description = params.incident.description
    paramsMap.amountToCharge = params.incident.amountToCharge
    paramsMap.isCharged = params.incident.isCharged ? false : true
    paramsMap.order = mROrderInstance

    def incidentInstance = new Incident(paramsMap)
    println "-----Done till here. Next line throws error----"
    if (incidentInstance.save(flush:true)){
        orderInstance.incident = incidentInstance

        result["result"] = true
    }else{
        result["result"] = false

        for (fieldErrors in incidentInstance.errors) {
            for (error in fieldErrors.allErrors) {
                println messageSource.getMessage(error, locale)
                result["message"] = messageSource.getMessage(error, locale)
            }
        }
    }
    return result
}
它给了我以下的错误-

ERROR: insert or update on table "order" violates foreign key     constraint "fk_a0y0jvv0o9nhkafuj7g7iknc6"
Detail: Key (incident_id)=(2) is not present in table "incident".. Stacktrace follows:
Message: ERROR: insert or update on table "order" violates foreign key constraint "fk_a0y0jvv0o9nhkafuj7g7iknc6"
Detail: Key (incident_id)=(2) is not present in table "incident".
Line | Method
->> 2102 | receiveErrorResponse in org.postgresql.core.v3.QueryExecutorImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1835 | processResults       in     ''
|    257 | execute . . . . . .  in     ''
|    500 | execute              in    org.postgresql.jdbc2.AbstractJdbc2Statement
|    388 | executeWithFlags . . in     ''
|    334 | executeUpdate        in     ''
|    124 | $tt__saveIncident .  in com.xyz.fleet.db.OrderService$$EPZ0qsAS
|     46 | doCall               in com.xyz.fleet.db.OrderService$_$tt__save_closure6$$EPZ0qsAS
|    815 | withTransaction . .  in org.grails.datastore.gorm.GormStaticApi
|    715 | withTransaction      in     ''
|     41 | $tt__save . . . . .  in com.xyz.fleet.db.MROrderService$$EPZ0qsAS
|     32 | $tt__save            in com.xyz.fleet.db.MROrderController
|    198 | doFilter . . . . . . in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter             in grails.plugin.cache.web.filter.AbstractFilter
|     53 | doFilter . . . . . . in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
|     49 | doFilter             in grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter
|     82 | doFilter . . . . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
|     46 | doFilterInternal     in org.grails.jaxrs.web.JaxrsFilter
|   1142 | runWorker . . . . .  in java.util.concurrent.ThreadPoolExecutor
|    617 | run                  in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . . . . . .  in java.lang.Thread
刷新会话时出错。即使我没有,每当它自动刷新时,它也会抛出相同的错误

注意:如果我没有手动刷新会话,则保存
事件
,该方法返回到保存
顺序
。这也节省了时间。
Incident
对象附加到Order对象,我可以使用
println
但在最后,当它自动清除会话时,会抛出如上所示的相同错误


最后,有人能告诉我这里的问题是什么吗?

最有可能的问题是
顺序。事件
不可为空(默认值),您试图保存顺序,而不先保存它的
事件

def order = ...
def incident = ...

if(incident.save()) {
    order.incident = incident
    order.save()
}
如果
事件
的实例只能属于单个
订单
,请尝试将
以下内容添加到

class Incident {
    Double amountToCharge
    String description
    Boolean isCharged = false
    Order order
    //..... few more variables

    static belongsTo = [order: Order]
}
双向多对一关联简化了保存实例

def order = ...
def incident = ...

order.incident = incident
order.save()

双向多对一关联导致
顺序
事件
一起保存。

您好,谢谢您的回复。不,事实上这不是nullable的情况,而是我正在创建
事件
对象和
顺序
对象并附加它们。但是当hibernate会话刷新时,PostgreSQL抛出一个错误,该错误(事件id)=(2)不在表“事件”中。当然,我会尝试向它们添加映射。如果您没有使用
belongsTo
它们,请确保在保存
订单之前保存
事件。您可以提前附加它们,但保存顺序很重要。