I am trying to insert employee record with List using @OneToMany mapping.
Entity Class Employee:
@Entity @Table(name = "employee") public class Employee { @Id @Column(name = "employee_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer employeeId; @Column(name = "employee_name") private String employeeName; @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JsonIgnoreProperties(allowSetters = true, value = { "employee" }) private List<EmployeePayroll> employeePayroll; } Entity Class EmployeePayroll:
@Entity @Table(name = "EmployeeSalary") public class EmployeePayroll { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false) private long salary; @Temporal(TemporalType.DATE) private Date fromDate; @Temporal(TemporalType.DATE) private Date toDate; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "employee_id", referencedColumnName = "employee_id") private Employee employee; } Request body:
{ "employeeName":"krishna", "employeePayroll":[ { "salary":200, "fromDate":"2015-01-01", "toDate":"2017-02-02" } ] } Service method:
public Integer createEmployee(Employee employee) { Employee savedEmployee = employeeRepository.save(employee); return savedEmployee.getEmployeeId(); } When I tried to call the API, I got org.springframework.dao.DataIntegrityViolationException.
could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement MYSQL Logs:
Query insert into employee (employee_name) values ('krishna') Query insert into employee_salary (employee_id, from_date, salary, to_date) values (null, '2015-01-01', 200, '2017-02-02') Looks like employee_id (Employee) value is not set to the EmployeePayroll entity on post insertof Employee.
How to resolve this issue ?