1

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 ?

2
  • did you specify a MySql dialect in your Hibernate configuration? Commented Oct 8, 2018 at 18:08
  • @rena Yes, specified the dialect Commented Oct 8, 2018 at 18:12

1 Answer 1

1

You are not setting the reference bidirectional : from EmployeePayroll -> Employee

One simple way is to set the reference before saving it:

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

and after save it:

Employee savedEmployee = employeeRepository.save(employee); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.