我使用下面的代码 -Grails的保存(冲洗:真)不会立即坚持到数据库
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]
}
请问你为什么试图异步添加你的子主题?如果您正在执行昂贵且长时间运行的进程,则异步可能会很有用,但我不确定这会有助于获得任何性能,而无需进行其他处理即可获得简单数据库插入的性能......此外,您将此代码放在哪里?它是否处于默认事务处理的服务方法中? – Philippe
上面的代码是精简版本。实际上有很长时间的运行任务发生,比如在子主题创建中调用Web服务等。 是代码在默认事务处于服务中。 – vishesh
好的,你可以粘贴你的Topic和Subtopic域类吗? – Philippe