我有两种方法可以使用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()
,但没有任何效果。
最佳答案
在保存之前,请尝试合并作业实例。 Merge()接受传递的实例,并将其与与该 session 关联的具有相同ID的任何对象合并。
关于java - Grails/hibernate 模式:DuplicateKeyException和NonUniqueObjectException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216093/