【发布时间】:2021-05-22 18:44:18
【问题描述】:
我有这个基本设置,但我真的不明白,为什么我会得到这样的行为
用户
@Entity
@Table(name = "USER")
@UserDefinition
public class User {
@Id
@SequenceGenerator(name = "userSeq", sequenceName = "ZSEQ_USER_ID", allocationSize = 1, initialValue = 1)
@GeneratedValue(generator = "userSeq")
@Column(name = "id", unique = true)
private Long id;
@OneToOne(cascade = CascadeType.ALL)
private Address address;
@OneToOne(cascade = CascadeType.ALL)
private ActivityForum activityForum;
@OneToMany(mappedBy="user",cascade = {CascadeType.ALL},fetch=FetchType.LAZY )
private List<Phone> phones = new ArrayList<>();
//ctor...
//getter/setter...
}
活动论坛
@Entity
@Table(name = "Actvity_Forum")
public class ActivityForum {
@Id
@SequenceGenerator(name = "afcSeq", sequenceName = "ZSEQ_af_ID",allocationSize = 1,initialValue = 1)
@GeneratedValue(generator = "afSeq")
@Column(name = "id", unique = true)
private Long id;
@OneToOne(mappedBy = "activityForum")
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
//ctor...
//getter/setter...
}
电话
@Entity
@Table(name ="PHONE")
public class Phone{
@Id
@SequenceGenerator(name = "phoneSeq", sequenceName = "ZSEQ_phone_ID", allocationSize = 1, initialValue = 1)
@GeneratedValue(generator = "phoneSeq")
@Column(name = "id", unique = true)
private Long id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name ="user_id", referencedColumnName="id")
private User user;
//ctor...
//getter/setter...
}
这是生成的 DB 布局。
我在 src 代码中留下了一些列以使帖子更短。
在我问这个问题之前,我做了一些研究,发现外键存储在关系所有者的表中。所有者由@JoinColumn 注释确定。它适用于电话多对一关系。
问题:为什么 Key 存储在 User 表中。而不是在 Activity 表中。
我正在使用什么。 爪哇 11 夸库斯 LTS 摇篮 6.71 MySQL数据库
【问题讨论】:
-
mappedBy 总是在关系的非拥有方中指定。在我看来也很奇怪,在同一属性上指定 mappedBy 和 joinColumn 时没有收到错误
-
mappedBy告诉 JPA '嘿,不要在这里寻找任何映射,这个关联已经 被其他类中的某个字段映射!当然,JPA 有义务,所以你的@JoinColumn被忽略了 -
谢谢。这解决了我的问题。如果你们中的某个人想将其作为答案发布,我将很乐意接受。否则,我会自己写一个更详细的解释。
标签: java mysql hibernate jpa quarkus