【问题标题】:JPA Hibernate foreign key is stored in the wrong tableJPA Hibernate 外键存储在错误的表中
【发布时间】: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


【解决方案1】:

使用@vincendep 和@crizzis 的cmets,我很快就发现了我的错误。

Explanation: 定义实体之间关系的方向对数据库映射没有影响。它只定义了我们在领域模型中使用该关系的方向。

对于双向关系,我们通常定义:

拥有方 逆或参考侧 @JoinColumn 注释帮助我们指定将用于加入实体关联或元素集合的列。另一方面,ma​​ppedBy 属性用于定义关系的引用方(非拥有方)

代码更改:

用户

@OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
private ActivityForum activityForum;

活动论坛

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;

生成的数据库布局:

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多