Hibernate在连接到子表时查找父字段名称

时间:2012-08-22 16:27:51

标签: java hibernate jpa

我的数据库中有三个表:

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似乎让它感到高兴。这是为什么?我不能模仿数据库中的关系吗?

1 个答案:

答案 0 :(得分: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,它将整个类层次结构折叠为一个表。