jpa hibernate:传递给持久化的分离实体

时间:2016-06-19 16:37:45

标签: hibernate jpa

传承下来的独立实体让我的生活变成了地狱,自从我遇到这个问题已经两天了,我已经尝试了这个网站上的所有内容,但没有任何作用。 所以我有两张桌子"模块"和"证明",我有一个模块的标题列表,我正在做的是取得该标题并检索模块,并且每个模块我想要证明我已创建。   在我的示例中我使用了ManyToMany关系

所以我有以下课程:

classe证明:

@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
}

classe模块:

@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";
}

class modulesService,create method:

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

1 个答案:

答案 0 :(得分:2)

我通过删除@GeneratedValue注释解决了这个问题。看起来没有其他选择对我有用(汽车或身份) 所以我做的是:我检索我的表的最大id,将其递增1,然后手动将其设置为我的实体。然后,当我坚持使用它时,它的效果非常好。