0

I'm a newbie in jpa. I have two entities with OneToMany / ManyToOne relationship. What I want: save a employee entity together with a mail entity at the same time. What I get: employee entity is saved into database. In the mail entity table I get null in the name column. In the employee_id column I get the the foreign key. I use postgres.

I followed this How to save parent and child in one shot (JPA & Hibernate)

Employee entity:

@JsonIgnore
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "employee_id")
    private Set<Mail> mails = new HashSet<Mail>();


public void addMail(Mail mail) {
        this.mails.add(mail);
        mail.setEmployee(this);
    }

Mail entity:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "employee_id")
private Employee employee;

Employee Controller:

@PostMapping("/employees")
    public Employee addEmployee(@RequestBody Employee employee){
        Mail mail2 = new Mail();
        employee.addMail(mail2);
        mail2.setEmployee(employee);
        return employeeService.save(employee);
    }

JSON I sent from Postmann:

{
    "name": "john",
    "salary": "5000",
    "birthday": "1900-01-01",
    "mails": 
        {
        "name": "john@gmail.com"
    }  
}

enter image description here

enter image description here

Zk_1990
  • 57
  • 5

0 Answers0