Bidirectional mapping null value is persisted in parent reference column in child

Viewed 144

Parent Entity

Employer (parent)

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "name")
private String name;

 @OneToMany( mappedBy = "employer",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    private List<Employee> empDetails = new ArrayList<>();

Employee (child)

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @ManyToOne(optional = false,fetch = FetchType.LAZY)
    @JoinColumn(name="emp_id", referencedColumnName = "id")
    private Employer employer;

Json from postman

{
    "name" : "data",
    "empDetails":[{
        "firstName" : "ttest",
        "lastName" : "te"
    }]
}

I'am trying to save in single save call like. Once parent is saved then child will be persisted automatically . But while doing so parent reference in child column is inserted with null.

3 Answers

mappedBy = "employer"

And here comes additional unneccessary text so I can post this.

Spring will not set employer value in your Employee instances. You should set them manually in controller:

    employer.getEmpDetails().forEach(e -> e.setEmployer(employer));

You have to reference in a way, the parent object in the child object in order to persist the id's parent correctly.

I think you have something like that:

Employer employer = new Employer("Employer");
Employee empX = new Employee("Employee 1", "My lastname")
employer.getEmpDetails().add(empX);

You could extend the constructor and set the parent reference:

Employer employer = new Employer("Employer");
Employee empX = new Employee("Employee 1", "My lastname", employer)
employer.getEmpDetails().add(empX);
Related