Java / Postgres / JPA:PersistentObjectException:传递给persist的分离实体

时间:2015-04-16 03:16:10

标签: java hibernate postgresql jpa

我和#34;代码"之间存在一对多的关系。和#34;代码系统" (代码系统有很多代码。)我使用以下代码实现了我的服务,以保存代码系统的代码:

服务

    code = new Code();
    code.setCode(valueConcept.getCode());
    code.setName(valueConcept.getDisplay_name());
    code.setValueSet(valueSet);
    code.setCodeSystem(codeSystem);
    code.setDateCreated(new Date());
    code.setDateUpdated(new Date());
    codeRepository.save(code);  

代码的最后一行是抛出异常。 "代码系统"是一个使用类似JPA存储库创建的对象。

为了实现这一对多关系,我有以下两个实体类:

Code.java

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "codeCode_idGenerator")
@Basic(optional = false)
@Column(name = "\"CODE_ID\"", nullable = false, insertable = false, updatable = false)
@SequenceGenerator(allocationSize = 1, name = "codeCode_idGenerator", sequenceName = "crisp_pophealth.application.code_id_seq", schema = "application", catalog = "crisp_pophealth")
public Integer getId() {
    return this.id;

}

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
@Basic(optional = true)
@JoinColumn(name = "\"CODE_SYSTEM_ID\"", nullable = true)
public CodeSystem getCodeSystem() {
    return this.codeSystem;

}

CodeSystem.java

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "codeSystemRecord_idGenerator")
@Basic(optional = false)
@Column(name = "\"RECORD_ID\"", nullable = false)
@SequenceGenerator(allocationSize = 1, name = "codeSystemRecord_idGenerator", sequenceName = "crisp_pophealth.application.code_system_id_seq", schema = "application", catalog = "crisp_pophealth")
public Integer getId() {
    return this.id;

}

@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST,
        CascadeType.MERGE }, mappedBy = "codeSystem")
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
@Basic(optional = false)
@Column(name = "\"RECORD_ID\"", nullable = false)
public Set<Code> getCodes() {
    return this.codes;

}

序列设置方式的原因是因为主键在每个postgres表上定义如下(作为示例):

    CREATE TABLE application.code ("CODE_ID" integer NOT NULL DEFAULT nextval('application.code_id_seq'::regclass),

注释这个关系存在的类的最佳方法是什么?我使用序列策略AUTO,因为数据库在创建时管理序列值。我尝试使用实体管理器保存失败,但我更希望所有持久性都由这些JPA存储库类管理。

0 个答案:

没有答案