JPA / Hibernate @SecondaryTable @PrimaryKeyJoinCloumn引用主表

时间:2016-09-22 02:43:01

标签: hibernate jointable

我有两张表primary_table和secondary_table。

hibernate实体定义如下:

@Entity
@Table(name = "primary_table")
@SecondaryTable(name = "secondary_table", pkJoinColumns =
@PrimaryKeyJoinColumn(name="secondary_id", referencedColumnName="secondary_id"))
public class Primary{
    ...
    @Id
    @Column(name = "primary_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long primaryId;

    ... columns in the primary table
    ... columns in the secondary table
}

表格如下:

CREATE TABLE primary_table
(
    primary_id INTEGER NOT NULL,
    secondary_id INTEGER NOT NULL,
    PRIMARY KEY( primary_id)
)
CREATE TABLE secondary_table
(
    secondary_id INTEGER NOT NULL,
    PRIMARY KEY( secondary_id)
)

简而言之:辅助列的主列引用了主表的非主列。

然而,在启动应用程序时,hibernate抱怨:

Caused by: org.hibernate.MappingException: Unable to find column with logical name: secondary_id in org.hibernate.mapping.Table(primary_table) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:828) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]

我已将referencedColumnName更改为主表的primary_id,实际上是让主键引用主键,并且满足hibernate。但是,我正在使用旧数据库,无法更改架构。

我的代码出了什么问题?

非常感谢!

1 个答案:

答案 0 :(得分:0)

辅助表的主列引用了主表的非主列,这就是问题所在。事实上,在主表和辅助表之间存在ManyToOne关系,它应该被处理并映射为ManyToOne,而不管这些表的语义如何。