无法使用@OneToMany Spring Boot插入数据

时间:2018-10-08 17:49:29

标签: hibernate spring-boot jpa spring-data-jpa

我正在尝试使用@OneToMany映射将员工记录插入到列表中。

实体类员工:

@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插入后,没有将employee_id(Employee)值设置为EmployeePayroll实体。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

您未设置双向引用:从EmployeePayroll-> Employee

一种简单的方法是在保存引用之前进行设置:

employee.getEmployeePayroll().forEach(EmployeePayroll::setEmployee);

并保存后:

Employee savedEmployee = employeeRepository.save(employee);