gpt4 book ai didi

hibernate - Grails save(flush:true)不会立即持久保存到数据库

转载 作者:行者123 更新时间:2023-12-02 14:50:52 25 4
gpt4 key购买 nike

我正在使用以下代码-

Topic topic = new Topic()
topic.name = "y u no save"
topic.save(flush:true, failOnError:true)

def promiseList = new PromiseList()
subtopicNames.each { sName ->
promiseList << Topic.async.task {
Subtopic subtopic = new Subtopic()
subtopic.name = sName
/* ... long running tasks like web service call ... */
log.info("Topic Id : $topic.id")
subtopic.topic = topic
subtopic.save(flush: true, failOnError: true)
}
}

def subtopics = promiseList.get()

我收到此错误-
Detail: Key (topic_id)=(517333) is not present in table "topic".; nested exception is org.postgresql.util.PSQLException: ERROR: insert or update on table "subtopic" violates foreign key constraint "fkfd7d3e7098cf2d58"
Detail: Key (topic_id)=(517333) is not present in table "topic".

当我检查数据库中ID为517333的主题时,它实际上不存在,而 aync.task块中的日志显示“主题ID:517333”。这是怎么回事,如何在需要时强制保存主题。
Topic - 

class Topic {
String name
static hasMany = [subtopics: Subtopic]
}

Subtopic -

class Subtopic {
String name
static belongsTo = [topic: Topic]
}

最佳答案

将域实例添加到使用hasMany关系的集合中的方法是将子域添加到父类的集合中。
试试这个 :

def promiseList = new PromiseList()
def topic = new Topic(name: 'main topic')
topic.save(failOnError: true, flush: true)
def subtopics = ['subtopic 1', 'subtopic 2']

subtopics.each { topicName ->
promiseList << Topic.async.task {
Subtopic subtopic = new Subtopic(name: topicName)
// adding to the topic will cascade saves of the subtopics by default.
topic.addToSubtopics(subtopic)
/* ... long running tasks like web service call ... */
return subtopic
}
}

// wait for tasks to complete
def subtopicList = promiseList.get()

// Saving the topic will cascade saves of the child subtopics
topic.save(failOnError: true, flush:true)

如果您仍然希望按照自己的方式进行操作,则可以禁用对subtopic的topic属性的约束以允许null:
class Subtopic {
//...
static constraints = {
topic nullable: true
}
}

然后,您可以执行以下操作:
Subtopic subtopic = new Subtopic(name : topicName)
subtopic.save(flush:true)

并且,在 promise 同步之后:
def subtopicList = promiseList.get()
subtopicList.each {
topic.addToSubtopics(it)
}
topic.save(failOnError: true, flush:true)

关于hibernate - Grails save(flush:true)不会立即持久保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30412607/

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