我创建了一个两个实体关系一对多(一个员工有多个地址)及其双向关系,如多对一。@Entity@Table(name = "Employees")@EntityListeners(AuditingEntityListener.class)public class Employee {@Id@GeneratedValue(strategy = GenerationType.AUTO)@Column(name="employee_id")private Long id;@NotBlankprivate String name;@NotBlankprivate String designation;@Temporal(TemporalType.TIMESTAMP)@LastModifiedDateprivate Date createdAt;@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)private List<Address> employee_address;和地址实体如下 @Entity@Table(name = "address")public class Address { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long address_id; @NotBlank @Column(name = "address_street", length = 250) private String street; @NotBlank @Column(name = "address_city", length = 50) private String city; @NotBlank @Column(name = "address_state", length = 50) private String state; @NotBlank @Column(name = "address_zipcode", length = 10) private String zipcode; @JsonIgnore @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "employee_id", nullable = false, referencedColumnName = "employee_id") private Employee employee;和 EmployeeController 保存数据如下@RestControllerpublic class EmployeeController { @Autowired EmployeeDAO employeeDAO; @Autowired AddressDAO addressDAO; @PostMapping("/employees") public void createEmployee(@Valid @RequestBody Employee emp) { Address address = null; List<Address> listAddresses = new ArrayList<Address>(); if (emp != null) { Employee employee = new Employee(); employee.setDesignation(emp.getDesignation());
2 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
在定义关系时的休眠中,您拥有关系的拥有方。关系的拥有方是粗略说的持有@JoinColumn 映射的一方。当调用 update/remove/persist 时,所有这些操作都是通过拥有方执行的。拥有集合时,您需要维护集合的两端。
当您向 Employee 添加新地址时,您需要确保该地址也具有对 Employee 的反向引用。您的 Employee 实体是您的关系的所有者。
如果您有类别 - 项目关系,并且您将一个项目从一个类别移动到另一个类别。将 Item 从 category1 列表移动到 category2 列表是不够的,您还需要更改 Item 中的反向引用。
森栏
TA贡献1810条经验 获得超5个赞
您需要取消注释该行:
address.setEmployee(employee);
在您的控制器中。
这是因为您定义了这样的映射:
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "employee_id", nullable = false, referencedColumnName = "employee_id")
private Employee employee;
nullable = false表明,必须有来自Adressto的引用Emplyee。但是错误可能来自对数据库的约束,即该列不能为空。
添加回答
举报
0/150
提交
取消