所以我有两个表:
Create Table annotation_table (Id varchar(255), Hash varchar(255), PRIMARY KEY (Id, Hash));
Create Table commit_table (Id varchar(255), Hash varchar(255), commit_Id varchar(255), PRIMARY KEY (Id, Hash), FOREIGN KEY (Id, Hash) references annotation_table (Id, Hash));
请注意,出于简化的原因,这两个表都已缩减为其基本值。两个表都映射到一个实体(也简化了):
@Table(name = "annotation_table")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@SecondaryTables({
@SecondaryTable(name = "commit_table", pkJoinColumns = {@PrimaryKeyJoinColumn(name="Id"), @PrimaryKeyJoinColumn(name="Hash")})
})
@IdClass(Key.class)
public class Annotation {
@Id
@Column(name = "Id")
private String id;
@Id
@Column(name = "Hash")
private String hash;
@Column(name = "commit_id", table = "commit_table")
private String commitHash;
}
I使用包含以下保存方法的存储库:
@Override
public void save(Annotation annot) {
em.getTransaction().begin();
annot = em.merge(annot);
em.persist(annot);
em.getTransaction().commit();
}
每次我试图创建一个注解并保存它时,我都会得到以下错误:
错误:无法添加或更新子行:外键约束失败(db_schema
.commit_table
,constraintcommit_table_ibfk_1
foreign key(Id
,Hash
)REFERENCESannotation_table
(Id
,Hash
))
该错误是由于JPA试图首先插入到";commit_table";然后变成";annotation_table";。
如何告诉JPA翻转查询顺序或自动完成其工作
好吧,我想好了。错误是由丢失的";referencedColumnName=";secondary表注释中的语句。固定代码如下:
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@SecondaryTables({
@SecondaryTable(name = "commit_table", pkJoinColumns = {@PrimaryKeyJoinColumn(name="Id", referencedColumnName = "Id"), @PrimaryKeyJoinColumn(name="Hash", referencedColumnName = "Hash")})
})
@IdClass(Key.class)
public class Annotation {
@Id
@Column(name = "Id")
private String id;
@Id
@Column(name = "Hash")
private String hash;
@Column(name = "commit_id", table = "commit_table")
private String commitHash;
}