Hi,
I’ve tried to upgrade from Hibernate 5.3.13.Final to 5.4.x, but i ran to the following problem, related to OneToOne unidirectional mapping:
I have two tables EMPLOYEES and EMP_DETAILS. The EMP_DETAILS is a child table of EMPLOYEES and has a foreign key to it. These are the CREATE SQL statements:
CREATE TABLE EMPLOYEES (
EMP_ID BIGINT NOT NULL,
NAME VARCHAR(252),
DEPARTMENT VARCHAR(128),
SALARY BIGINT,
PRIMARY KEY (EMP_ID)
);
CREATE TABLE EMP_DETAILS (
ED_ID BIGINT NOT NULL,
EMP_ID BIGINT,
ADDRESS VARCHAR(252),
GENDER VARCHAR(8),
BANK_ACCOUNT VARCHAR(128),
PRIMARY KEY (ED_ID),
FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEES(EMP_ID)
);
These are the entities:
@Entity
@Table(name="EMPLOYEES")
public class Employee {
@Id
@Column(name="EMP_ID", unique = true, nullable = false)
private Long empId;
private String name;
private String department;
private Long salary;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "EMP_ID")
private EmpDetails empDetails;
//getters and setters
}
@Entity
@Table(name="EMP_DETAILS")
@Data
public class EmpDetails {
@Id
@Column(name="ED_ID", unique = true, nullable = false)
private Long edId;
private String address;
private String gender;
@Column(name="BANK_ACCOUNT")
private String bankAccount;
@Column(name="EMP_ID")
private Long empId;
//getters and setters
}
When I create an Employee object with its corresponding EmpDetails one and try to persist the Employee, an exception is getting thrown because hibernate tries to persist the child table (EMP_DETAILS) first:
Hibernate: insert into EMP_DETAILS (address, BANK_ACCOUNT, EMP_ID, gender, ED_ID) values (?, ?, ?, ?, ?)
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The INSERT statement conflicted with the FOREIGN KEY constraint "FK__EMP_DETAI__EMP_I__07E417F5". The conflict occurred in database "xxxx", table " EMPLOYEES", column 'EMP_ID'.
The behavior in Hibernate 5.3.13.Final is different. It persists the EMLOYEES and then tries to persist the EMP_DETAILS.
Hibernate: insert into EMPLOYEES (department, name, salary, EMP_ID) values (?, ?, ?, ?)
Hibernate: insert into EMP_DETAILS (address, BANK_ACCOUNT, EMP_ID, gender, ED_ID) values (?, ?, ?, ?, ?)
Which behavior is the correct one? In 5.4.x or in 5.3.13.Final?