Grails / Hibernate:DuplicateKeyException和NonUniqueObjectException

时间:2017-02-14 00:54:02

标签: java hibernate grails

我有几种使用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"])
 }

我添加了@Transactionaljob.attach()job.refresh(),但没有任何效果。

1 个答案:

答案 0 :(得分:0)

尝试在保存之前合并您的作业实例。 Merge()接受传递的实例,并将其与任何与会话关联的id相同的对象合并。