hibernate - 在休眠中一对一映射的父类中保存关系ID
问题描述
我有两个简单的类,称为 Student 和 Location
@Entity
public class Student {
private String name;
private Integer id;
@OneToOne(fetch = FetchType.EAGER, mappedBy = "student", cascade = CascadeType.PERSIST)
@JsonProperty("location")
private Location location;
/* Getters and Setters */
}
@Entity
public class Location {
private Integer id;
private String locationName;
private String street;
private String postalCode;
@OneToOne(fetch = FetchType.EAGER)
@PrimaryKeyJoinColumn
@JoinColumn(name = "student_id")
private Student student;
/* Getters and Setters */
}
目前,该模式是这样的,即学生的id
存储在位置表中,但在逻辑上Location
独立于Student
实体。它Student
应该有Location
实体的ID
根据我在网上看到的所有示例,在我的案例Location
中,它的子类最终具有映射关系。我尝试通过在变量上设置属性来反转mappedby
属性,private Student student;
但它似乎没有在数据库中创建该列。
我在 REST 请求中得到的 JSON 的结构如下:
"students": [
{
"id": 1234,
"name": "John Doe",
"location": {
"id": "5678",
"locationName": "St.Mary",
"street": "Wellington St",
"postalCode": "41298"
}
},
.
.
.
.
/* Can have more students here */
]
所以数据库明智这就是我希望架构看起来像的样子:
students
id name location_id
locations
id location_name street postal_code
有人可以指出我正确的方向。我真的很感激这方面的一些帮助,因为我已经被这个问题困扰了一段时间
解决方案
Location
是参考表。参考表应使用@ManyToOne
注释进行映射。Location
如果可以更简单地处理数据,则可以立即加载。但我更喜欢默认的惰性方法。也不@JoinColumn
是必需的(默认情况下使用它)。但它使映射更清晰,可用于指定连接列名称。注释也@ForeignKey
可用于指定外键约束名称。
@Entity
public class Student {
@Id
private Integer id;
@Column
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Location location;
}
@Entity
public class Location {
@Id
private Integer id;
@Column
private String locationName;
}
推荐阅读
- makefile - 为子目录编写通用 Makefile 规则
- javascript - 如何让 Webpack 从我的 node_modules 加载文件夹?
- python - Scrapy 从一个文件运行多个蜘蛛
- ios - 在手机上本地存储数据是否安全?
- .net - 转换为 Lamar - 注册 - 使用 StructureMap 的这段代码的等价物是什么?
- http - 如何检查在 TLS/SSL 握手期间是否进行主机名验证?
- bazel - 如何将规则限制为 cpp 工具链的子集?
- c++ - Open MP 中的冒泡排序较慢
- woocommerce - 是否可以像 woocommerce 默认更新的其他状态一样以颜色突出显示这些状态?
- elasticsearch - Elasticsearch 如何从动态映射中排除字段