hibernate - jpa hibernate : detached entity passed to persist

标签 hibernate jpa

分离的实体传递给持久化把我的生活变成了 hell ,自从我遇到这个问题以来已经两天了,我已经尝试了这个网站上的所有方法,但没有任何效果。 所以我有两个表“模块”和“证明”,我有一个模块标题列表,我正在做的是获取该标题并检索模块,对于每个模块,我想放置我已经创建的证明。 在我的示例中,我使用ManyToMany关系

所以我有以下类(class):

类证明:

@Entity
@Table(name = "edep_attestations")
public class Attestation implements Serializable {
private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
       private Long id;
       private String title;
       ...
       @ManyToMany(mappedBy="attestations")
       private Set<Module> modules = new HashSet<>();

       // getters and setters
}

类模块:

@Entity
@Table(name = "edep_modules")
public class Module implements Serializable {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     protected Long id;
     private String title; 
     ...
     @ManyToMany(fetch = FetchType.EAGER,cascade = {CascadeType.MERGE})
     private Set<Attestation> attestations = new HashSet<>();
    // getters and setters 
}

这是我在我的 bean 中使用的方法

public String create(){
    Module m = null;
    this.attestationsService.create(attestation);
    for (String title : moduleTitles) {
            m = modulesService.getModulebyTitle(title);
            m.getAttestation().add(attestation); 
            this.modulesService.create(m);
    }
    return "success";
}

类modulesService,创建方法:

public void create(E object) throws Exception {
    em.clear();
    em.persist(object);
    em.flush();
}

最佳答案

我通过删除 @GenerateValue 注释解决了这个问题。看起来没有其他选项对我有用(自动或身份)。
那么我要做的就是:检索表的最大 id,将其加一,然后手动将其设置为我的实体。当我保留该对象时,它工作正常。

关于hibernate - jpa hibernate : detached entity passed to persist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37909490/

相关文章:

performance - Persistence.createEntityManager()与Hibernate一起非常缓慢

java - 处理多个插入的最佳方法

java - 通过 Hibernate 使用分离对象删除行和引用

java - Criteria API 查询失败

java - 如何调用 Spring 框架存储库方法

java - HibernateUtil 类的一个好的替代通用名称是什么?

java - Struts + hibernate : large memory consumption arise during reading big data arrays

java - 同一个 JPA 类的多个数据库支持

java - Spring + hibernate + quartz : Dynamic Job

java - JPA事务处理