java - Grails/hibernate 模式:DuplicateKeyException和NonUniqueObjectException

标签 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(),但没有任何效果。

最佳答案

在保存之前,请尝试合并作业实例。 Merge()接受传递的实例,并将其与与该 session 关联的具有相同ID的任何对象合并。

关于java - Grails/hibernate 模式:DuplicateKeyException和NonUniqueObjectException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216093/

相关文章:

Java 持久性复合 ID

grails - Grails 生成 Controller 中的新代码

grails - grails 域类中何时以及为什么应该为空或/和空白约束?

java socket InputStream 在客户端和服务器上挂起/阻塞

java - JAX-RS:提供 "default"子资源定位器

java - 查明文本是否太长而无法显示并且需要换行

java - XML 文件无法引用类文件

java - JPQL 中等效的 SQL ANY 运算符是什么?

java - 集合的自定义 Hibernate 插入,@WhereJoinTable 的对应物

grails - Grails可搜索插件