首页 > 解决方案 > 我在两张表之间建立了关系,但是

问题描述

我在两个表之间建立了关系,但是当我调用表时,一些数据为空。我可能无法在标题中很好地解释自己,但下面列出了代码及其输出。

这是部门实体

@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

标签: javaspring-data-jpa

解决方案


如果 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;

推荐阅读