使用@Inheritance JPA属性时无效的插入顺序

时间:2012-06-25 15:23:27

标签: java inheritance jpa jpa-2.0 eclipselink

我在DB2 DB上调整了Eclipselink持久性提供程序。下面列出了简化定义的3个表:

CREATE TABLE root
(
    id       CHAR(32) NOT NULL PRIMARY KEY,
    rec_type VARCHAR(20)
);

CREATE TABLE derived
(
    id CHAR(32) NOT NULL PRIMARY KEY,
    ...
);
ALTER TABLE derived ADD CONSTRAINT fk_derived_to_root FOREIGN KEY (id) REFERENCES root(id);

CREATE TABLE secondary
(
    derived_id NOT NULL PRIMARY KEY,
    ...
);
ALTER TABLE secondary ADD CONSTRAINT fk_secondary_to_derived FOREIGN KEY (derived_id) REFERENCES derived(id);

下面列出了这些实体的Java实体类, RootEntity:

@javax.persistence.Table(name = "ROOT")
@Entity
@DiscriminatorColumn(name = "REC_TYPE")
@Inheritance(strategy = InheritanceType.JOINED)
public class RootEntity {
    private String id;

    @javax.persistence.Column(name = "ID")
    @Id
    @GeneratedValue(generator = "system-uuid")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    private String principalType;
    @Column(name = "PRINCIPAL_TYPE")
    public String getPrincipalType() {
        return principalType;
    }

    public void setPrincipalType(String principalType) {
        this.principalType = principalType;
    }
   ...
}

DerivedEntity:

@javax.persistence.Table(name = "DERIVED")
@Entity
@DescriminatorValue("DERIVED")
public class DerivedEntity extends RootEntity {
    private SecondaryEntity secondaryEntity;

    @OneToOne(mappedBy = "derived_id")
    public SecondaryEntity getSecondaryEntity() {
        return secondaryEntity;
    }

    public void setSecondaryEntity(SecondaryEntity secondaryEntity) {
        this.secondaryEntity = secondaryEntity;
    }
 ...
}

我在测试日志中看不到派生表插入:

--INSERT INTO ROOT (ID, REC_TYPE) VALUES (?, ?)
    bind => [241153d01c204ed79109ce658c066f4c, Derived]
--INSERT INTO SECONDARY (DERIVED_ID, ...) VALUES (?, ...)
    bind => [241153d01c204ed79109ce658c066f4c, ...]
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.ibm.db2.jcc.am.fo: DB2 SQL Error: SQLCODE=-530, SQLSTATE=23503, SQLERRMC=SCHEM.SECONDARY.FK_SECONDARY_TO_DERIVED, DRIVER=3.57.82

所以问题是:为什么Eclipselink在插入DERIVED表之前不会在SECONDARY表中插入新记录?

P.S。没有SECONDARY表(仅ROOTDERIVED表)或没有使用继承(DERIVED表生成id)时,一切正常。

1 个答案:

答案 0 :(得分:2)

对于继承,JPA假定相关表中的外键约束引用根表。

您可以更改约束以引用根表,或

使用DescriptorCustomizer进行设置,

descriptor.setHasMultipleTableConstraintDependecy(true);

,或者

定制器OneToOneMapping使其外键引用辅助表(JPA注释总是使其引用根表)。

请记录一个错误,因为JPA连接列应允许您定义辅助表的外键。

EclipseLink将插入推迟到辅助表的原因是允许按表对插入进行分组以允许批量写入并避免数据库死锁。