OneToMany关系和复合主键级联

时间:2015-06-23 09:26:15

标签: java hibernate jpa

我正在使用JPA(Hibernate)并尝试使用子项和复合键来保持整个新实体,但是当持久化子项时,我在键中得到null。表结构:

CREATE TABLE IDENTITY_DOCS
(
    PERSON_ID BIGINT NOT NULL,
    DOC_TYPE_ID BIGINT NOT NULL,
    ...
);

CREATE TABLE DOC_TYPES
(
    DOC_TYPE_ID BIGINT PRIMARY KEY NOT NULL,
    ...
);

CREATE TABLE PERSONS
(
    PERSON_ID BIGINT PRIMARY KEY NOT NULL,
    ...
);

映射:

@IdClass(...IdentityDocsPK.class)
@Table(name = "IDENTITY_DOCS")
@Entity
public class IdentityDocs {

    @Id
    @Column(name = "PERSON_ID", nullable = false)
    private Long personId;

    @Id
    @Column(name = "DOC_TYPE_ID")
    private Long docTypeId;

    @ManyToOne
    @MapsId("personId")
    @JoinColumn(name = "PERSON_ID", referencedColumnName = "PERSON_ID")
    private Employee employee;
    ...
}

public class IdentityDocsPK implements Serializable {

    private Long personId;

    private Long docTypeId;
    ...
}

@Table(name = "PERSONS")
@Entity
@Where(clause = "PERSON_TYPE_ID = 1")
public class Employee {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "PERSON_ID")
    @Id
    private Long personId;
    ...
    @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private List<IdentityDocs> identityDocs;
}

@Table(name = "DOC_TYPES")
@Entity
public class DocTypes {

    @Id
    @Column(name = "DOC_TYPE_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long docTypeId;
    ...
}

测试用例:

Employee employee = new Employee();
employee.setFirstName("AAAA");
employee.setLastName("BBBB");
employee.setPersonNumber("1337");

IdentityDocs docs1 = new IdentityDocs();
docs1.setDocTypeId(1L); // already in database
docs1.setDocNumber("11111");
docs1.setDocSeries("11111");
docs1.setPlaceIssue("1111");

employee.setIdentityDocs(new ArrayList<IdentityDocs>());
employee.getIdentityDocs().add(docs1);

em.persist(employee); 

错误代码:

NULL not allowed for column "PERSON_ID"; SQL statement:
insert into IDENTITY_DOCS (DATE_EXPIRED, DATE_ISSUE, DOC_NUMBER, DOC_SERIES, PLACE_ISSUE, DOC_TYPE_ID, PERSON_ID) values (?, ?, ?, ?, ?, ?, ?) 

我也试过没有@MapsId(在相关字段上使用insertable = false,updatable = false),但结果相同。问题@OneToMany and composite primary keys?是相关的,但我在那里找不到答案

1 个答案:

答案 0 :(得分:0)

也许你的DDL中的person_id字段应该有一个AUTO_INCREMENT子句,或者以其他方式生成密钥。