我的数据库中有三个表:
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 实体管理器一起使用时,它会报错并出现以下错误:
无法在 org.hibernate.mapping.Table(A) 及其相关的 super 表和辅助表中找到逻辑名称为 B_ID 的列
将 C 到 B 连接的 referencedColumnName
更改为 A_ID
似乎让它很开心。这是为什么?我不能像数据库中那样对关系进行建模吗?
最佳答案
缺少的是继承策略的规范:
@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
,它将整个类层次结构折叠到一个表中。
关于java - Hibernate 在连接到子表时寻找父字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077494/