无法使用@OneToMany Spring启动插入数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (184)

我正在尝试使用@OneToMany映射插入带有List的员工记录。

实体类员工:

@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实体。

如何解决这个问题?

提问于
用户回答回答于

您没有设置双向参考:来自EmployeePayroll - > Employee

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

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

保存后:

Employee savedEmployee = employeeRepository.save(employee);

扫码关注云+社区

领取腾讯云代金券