Я пытаюсь вставить запись сотрудника со списком, используя сопоставление @OneToMany.
Класс сущности 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;
}
Класс сущности 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;
}
Запростело:
{
"employeeName":"krishna",
"employeePayroll":[
{
"salary":200,
"fromDate":"2015-01-01",
"toDate":"2017-02-02"
}
]
}
Метод обслуживания:
public Integer createEmployee(Employee employee) {
Employee savedEmployee = employeeRepository.save(employee);
return savedEmployee.getEmployeeId();
}
Когда я пытался вызвать API, я получил 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:
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')
Похоже, что значение employee_id (Employee) не задано для объекта EmployeePayroll после вставки сообщения Employee.
Как решить эту проблему?