[英]Why Spring JPA Bidirectional OneToMany and ManyToOne is not updating the foreign key column?
[英]JPA Entity best way for ManyToOne Bidirectional Relationship with Foreign Key
考虑下表结构和关系。
Teacher
id(pk),
tname,
subject_id(fk),
subject_name
Subject
sid(pk),
sname,
subject_learning_curve
TEACHER(关系所有者)到 SUBJECT 多对一,双向关系
我在 intellij 中使用了持久性工具window 。 它基于数据源自动为数据库中的所有关系生成实体。
在实体中它是这样生成的
@Entity
//using lombok for getters and setters
public class TEACHER{
@Id
@GeneratedValue
private Long id;
private String tname;
private long subject_id;
private String subject_name;
@ManyToOne
@JoinColumn(name = "subject_id",referencedColumnName="sid")
private Subject subjectBySid; //is this fine to have a reference like this
}
或下面的第二种方法
@Entity
//using lombok for getters and setters
public class Teacher{
@Id
@GeneratedValue
private Long id;
private String tname;
@ManyToOne
@JoinColumn(name = "subject_id",referencedColumnName="sid")
private Subject subject; //or just this it will suffice all use case,like if i just want to read Teacher data and just the sid not the whole subject row
}
同样,主题也将具有指向教师表的参考。
基于以下几点,有人可以提供见解。
@JoinColumn(name = "subject_id",referencedColumnName="sid")
中获取该特定字段@JoinColumn(name = "subject_id",referencedColumnName="sid")
注释会解决这个问题,它应该在 TEACHER.subject_id 中具有价值以下是我对您的问题的回答和建议:
1.以上两种写实体的方式,哪一种是最理想和正确的。
方法 2 是编写实体的正确方法。 一旦您定义了与另一个实体的
@ManyToOne
关系,就无需定义特定于该实体的列。
2. 从 Hibernate 和 JPA 的角度来看哪个更高效。
JPA is the specification for management of relational data in Java and Hibernate is the Object-Relational Mapping(ORM) tool that saves the state of objects into DB. 简单来说,Hibernate就是JPA的实现。 因此,比较它们不应该是一个问题。 您可以将 Hibernate 与其他可与 Spring 框架(如 iBatis、EclipseLink 等)一起使用的 ORM 工具进行比较。
3. 根据我选择编写实体的方法生成的 sql 会有什么不同吗?
不,生成的 SQL 将是相同的。 但是,要生成 SQL,您可以使用不同的方法,例如
@NativeSqlQuery
、Hibernate Query Language(HQL)
等。
4.如果我采用第二种方法,查询记录并将其保存到数据库或检索会更容易。
您绝对应该使用第二种方法来实现清晰、直接和相关的方法。 如果您考虑面向对象语言和关系数据库管理的原则,则第一种方法的核心是错误的。 当您可以通过映射轻松链接它们时,无需创建额外的列、代码、实体属性和其他错误。
5.当我在实体中获取数据时,TEACHER 中的 subject_id 是否有价值,或者它只是一个名为 subject 的引用,我不会在 TEACHER.subject_id 或 @JoinColumn(name = "subject_id",referencedColumnName= 中获取该特定字段"sid") 注释会解决这个问题,它应该在 TEACHER.subject_id 中具有价值
在您的数据库中,您的
Teacher
表中应该有一个subject_id
列,该列将作为外键并引用Subject
表的sid
列。 这发生在数据库端。
在您的面向对象端(Spring),您可以使用创建 object 参考为Subject
to map withStudent
,或者您可以直接使用HQL 或 NativeQuery中的字段subject_id
来执行数据库操作并保存数据。 因此,您将在Teacher
实体中获得subject_id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.