gpt4 book ai didi

java - hibernate composite 主键包含一个复合外键,如何映射这个

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:11:09 25 4
gpt4 key购买 nike

我在那里搜索,没有找到任何类似的主题,所以我发布了一个新问题。

我在现有数据库上使用 Hibernate。我们不允许更改表结构和数据。应用程序正在从数据库中读取数据并根据某种逻辑迁移到另一个数据存储区。

现在的问题是关于复合PK映射。例如

表 A 具有复合 PK。

Table A
--------
a1 (pk)
a2 (pk)
a3 (pk)
a4 (pk)
foo
bar
========

B表也有一个复合PK,这个复合PK的一部分是A的PK,这里也作为FK。

Table B
--------
a1 (fk,pk)
a2 (fk,pk)
a3 (fk,pk)
a4 (fk,pk)
b1 (pk)
b2 (pk)
b3 (pk)
foo
bar
========

我尝试了几种方法,但都没有用。谁能告诉一个有效的 Hibernate 映射解决方案?注释样式更好。

最佳答案

将A的实体对象设置为B的pk类中的@ManyToOne。

如果你有

Class A
Class APK - A's Primary Key

Class B
Class BPK - B's primary Key.

BPK 将包含 A 作为属性

@Embeddable
public class BPK implements serializable {
....
private A a;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumns ({
@JoinColumn(name="...", referencedColumnName = "..."),
@JoinColumn(name="...", referencedColumnName = "..."),
...
})
public getA() {
return this.a;
}
}

来自documentation

@Embeddable inherit the access type of its owning entity unless the Hibernate specific annotation @AccessType is used. Composite foreign keys (if not using the default sensitive values) are defined on associations using the @JoinColumns element, which is basically an array of @JoinColumn. It is considered a good practice to express referencedColumnNames explicitly. Otherwise, Hibernate will suppose that you use the same order of columns as in the primary key declaration.

关于java - hibernate composite 主键包含一个复合外键,如何映射这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com