Utku Kilincci
Utku Kilincci

Reputation: 26

I made a relationship between the two tables but

I made a relationship between the two tables, but when I call the table the some data is null. I may not explain myself well in the title, but the codes and their outputs are listed below.

Here is Department Entity

@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;

And Doctor Entity

@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;

When I send this JSON to Postman,

{
"departmentEntity":{
    "name":"departmentName",
    "polyclinicNo":"911",
    "doctorEntity":[
        {
            "name":"doctorName",
            "profession":"professionName"
        }
    ]
}

it is saved in the doctor table like this.

  {
        "doctorEntity": {
            "id": 1,
            "name": "doctorName",
            "profession": "professionName",
            "departmentEntity": null
        }
    }

The department field is saved as null in the doctor table. So how can i show the department information at the doctor table. Same time when i add the doctor information with department information in to the doctor table and i call the department table, doctor information in the department field appears null.

Sorry for my bad England xd

Upvotes: 0

Views: 107

Answers (1)

fkrsc
fkrsc

Reputation: 151

If you have bidirectional relationship between Department and Doctor entities, you have to define owner of relationship. The owning side is usually defined on the many side of relation which owns the foreign key. The referencing side is defined using by mappedBy attibute.

Department Entity

@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;

Doctor Entity

@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;

Upvotes: 1

Related Questions