保存实体时,通过 @OneToMany
关系不会保存到它们的表中。我不明白怎么了。
员工:
@Entity
@Table(name = "EMPLOYEE", schema = PUBLIC)
public class Employee {
private String name;
private String lastname;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
List<EmployeePhoneNumber> employeePhoneNumbers = new ArrayList<>();
}
员工姓名:
@Entity
@Table(name = "EMPLOYEE_PHONES", schema = PUBLIC)
public class EmployeePhoneNumber {
@Id
@SequenceGenerator(allocationSize = 1, name = "SEQ_EMPLOYEE_PHONES", schema = PUBLIC,
sequenceName = "EMPLOYEE_PHONES_ID_SEQ")
@GeneratedValue(generator = "SEQ_EMPLOYEE_PHONES", strategy = GenerationType.SEQUENCE)
@Column(name = "ID", unique = true, nullable = false)
private Long id;
@ManyToOne
@JoinColumn(name = "employee_id", referencedColumnName = "id",
nullable = false, insertable = false, updatable = false)
private Employee employee;
@Column(name = "PHONE_NUMBER", unique = true, nullable = false)
private String phoneNumber;
@Enumerated(EnumType.STRING)
@Column(name = "NUMBER_TYPE", nullable = false)
private PhoneNumberType phoneNumberType;
}
如何设置这些字段并保存实体:
EmployeePhoneNumber workPhone = new EmployeePhoneNumber();
workPhone.setPhoneNumber(workPhone);
workPhone.setPhoneNumberType(PhoneNumberType.WORK_PHONE);
EmployeePhoneNumber mobilePhone = new EmployeePhoneNumber();
mobilePhone.setPhoneNumber(mobilePhone);
mobilePhone.setPhoneNumberType(PhoneNumberType.MOBILE_PHONE);
EmployeePhoneNumber corporatePhone = new EmployeePhoneNumber();
corporatePhone.setPhoneNumber(corporatePhoneNumber);
corporatePhone.setPhoneNumberType(PhoneNumberType.CORPORATE_PHONE);
List<EmployeePhoneNumber> employeePhoneNumbers = employee.getEmployeePhoneNumbers();
employeePhoneNumbers.add(workPhone);
employeePhoneNumbers.add(mobilePhone);
employeePhoneNumbers.add(corporatePhone);
employee.setEmployeePhoneNumbers(employeePhoneNumbers);
employeeRepository.save(employee);
方法完成后,我没有一个错误,一切都正常,只有表格没有填写-为什么?
1条答案
按热度按时间iyfamqjs1#
您还必须在employeephoneumber中设置employee引用,因为hibernate将使用它来保存它。
最好的解决方案是在雇员身上创建一个addemployeephoneumber方法,如下所示:
这样你就不会忘记确定双方的关系。