java - 我在两张表之间建立了关系,但是
问题描述
我在两个表之间建立了关系,但是当我调用表时,一些数据为空。我可能无法在标题中很好地解释自己,但下面列出了代码及其输出。
这是部门实体
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(name = "POLIKLINIK_NO" ,nullable = false, unique = true)
private String polyclinicNo;
@OneToMany(targetEntity = DoctorEntity.class, cascade = CascadeType.ALL)
@JoinColumn(name = "fk", referencedColumnName = "id")
private Collection<DoctorEntity> doctorEntity;
和医生实体
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String profession;
@ManyToOne(targetEntity = DepartmentEntity.class, cascade = CascadeType.ALL)
@JoinColumn(name = "dp", referencedColumnName = "id")
private DepartmentEntity departmentEntity;
当我将此 JSON 发送给 Postman 时,
{
"departmentEntity":{
"name":"departmentName",
"polyclinicNo":"911",
"doctorEntity":[
{
"name":"doctorName",
"profession":"professionName"
}
]
}
它像这样保存在医生表中。
{
"doctorEntity": {
"id": 1,
"name": "doctorName",
"profession": "professionName",
"departmentEntity": null
}
}
部门字段在医生表中保存为空。那么我如何在医生桌上显示部门信息。当我将带有部门信息的医生信息添加到医生表中并调用部门表时,部门字段中的医生信息显示为空。
对不起我糟糕的英格兰xd
解决方案
如果 Department 和 Doctor 实体之间存在双向关系,则必须定义关系的所有者。拥有方通常定义在拥有外键的关系的多方上。引用端由 mappedBy 属性定义。
部门实体
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(name = "POLIKLINIK_NO" ,nullable = false, unique = true)
private String polyclinicNo;
@OneToMany(mappedBy="department", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<DoctorEntity> doctorEntity;
医生实体
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String profession;
@ManyToOne
@JoinColumn(name = "department_id", referencedColumnName = "id")
private DepartmentEntity departmentEntity;
推荐阅读
- codeigniter-3 - 错误库 fpdf
- javascript - 文本标签隐藏在圆圈 d3 中
- angular - 无法解析服务的所有参数
- javascript - 我的代码使用 Linq To Sql 创建两个外部和一个内部 JSON 列表
- appium-android - android appium optionalIntentArguments 多个布尔额外参数
- tensorflow - 适应文本分类器神经网络以接受多个类别
- laravel - 如何从组件内的路由器链接渲染嵌套路由?
- css - 背景 CSS 中的中心图标
- html2canvas - DOMException:无法在“ShadowRoot”上设置“adoptedStyleSheets”属性:不允许在多个文档中共享构造的样式表
- javascript - 二元和一元函数表达式的流多态类型定义