2

我的数据库中有三个表:

create table A (
  a_id int primary key
);

create table B (
  b_id int primary key references A(a_id)
);

create table C (
  c_id int primary key,
  b_id int references B(b_id)
);

我使用以下 JPA 注释类对它们进行建模:

@Entity(name = "A")
@Table(name = "A")
public class A {
    @SuppressWarnings("unused")
    @Id
    @Column(name = "A_ID")
    private int id;
}

@Entity(name = "B")
@Table(name = "B")
@PrimaryKeyJoinColumns({@PrimaryKeyJoinColumn(name = "B_ID", referencedColumnName = "A_ID")})
public class B extends A {
}

@Entity(name = "C")
@Table(name = "C")
public class C {
    @SuppressWarnings("unused")
    @Id
    @Column(name = "C_ID")
    private int id;

    @SuppressWarnings("unused")
    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumns(value = {
        @JoinColumn(name = "B_ID", referencedColumnName = "B_ID", insertable = false, updatable = false)})
    private B b;
}

当我尝试将这些类与 Hibernate 实体管理器一起使用时,它会抱怨以下错误:

Unable to find column with logical name: B_ID in org.hibernate.mapping.Table(A) and its related supertables and secondary tables

将 C更改referencedColumnName为 B 加入A_ID似乎让它很开心。这是为什么?我不能对数据库中的关系进行建模吗?

4

1 回答 1

1

缺少的是继承策略的规范:

@Entity(name = "A")
@Table(name = "A")
@Inheritance(strategy = InheritanceType.JOINED)
public class A {
    @SuppressWarnings("unused")
    @Id
    @Column(name = "A_ID")
    private int id;
}

JPA 默认为SINGLE_TABLE,它将整个类层次结构折叠到一个表中。

于 2012-08-23T08:07:02.413 回答