【发布时间】:2017-02-14 00:54:01
【问题描述】:
我有几个使用 GORM 检索数据以及更新和保存的方法。抛出以下错误。
2017-02-14 01:39:02,316 [ERROR ] A different object with the same identifier value was already associated with the session : [com.example.Job#3365090]; nested exception is org.hibern$
org.springframework.dao.DuplicateKeyException: A different object with the same identifier value was already associated with the session : [com.example.Job#3365090]; nested exception is org.hibernate.Non$
at com.example.job.JobDaoService.$tt__persistJob(JobDaoService.groovy:88)
at com.example.job.JobDaoService.$tt__changeJobStatusByJob(JobDaoService.groovy:225)
...
Caused by: org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.example.Job#3365090]
... 23 more
我的方法是: (1)
Job persistJob(Job job) throws JobException {
job.save(flush: true)
if (job.hasErrors()) {
throw new JobException("Error (ID: ${job?.id}). Details: ${job.errors}", JOB_CANNOT_BE_CREATED_EXCEPTION)
}
return job
}
(2)
@Synchronized
Job changeStatusByJob(Job job, JobStatus jobStatus) {
job.refresh()
job.status = jobStatus
if (persistJob(job)) {
log.info("The status is changed.")
}
return job
}
(3)
@Transactional
Job getPendingJob() throws JobException {
return Job.findByStatusAndCreatedLessThanEquals(READY, new Date(), [sort: "type"])
}
我添加了@Transactional、job.attach()、job.refresh(),但没有任何效果。
【问题讨论】:
-
约伯长什么样子?有没有双向关系?这些是急切的吗?
-
是的,它具有双向关系并且急切地获取数据,但在持久化作业之前不会更新。我刚刚读取了关系表的值。
-
好吧。如果有这样的关系,很可能是非唯一对象异常的原因,因为该对象在会话中被加载了两次...
-
尝试 - 只是为了好玩 - 删除“fetch: eager” - 并为工作关系创建一个吸气剂。并在你需要关系的地方使用吸气剂。要点是,在制作
Job.findByStatus ...时,请确保只有一个 Job 实例加载到会话中。也就是说,你不能从工作 -> 工作状态 -> 工作(如果那是你的关系):)