我正在创建订单,后来又将员工分配给该订单。所以我很难在这两者之间建立联系。我的订单表没有更新employee_id列
我的员工班级
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "servedBy")
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private List<Orders> orders;
...
}
我的订单类
@Entity
public class Orders {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Embedded
private OrderStatus orderStatus;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee servedBy;
...
}
代码我试图将这两个映射到哪里
public void orderServed(Long employeeId, Long orderId) {
Orders order = orderRepository.findOne(orderId);
Employee employee = employeeRepository.findOne(employeeId);
List<Orders> orders = employee.getOrders();
orders.add(order);
employee.setOrders(orders);
employeeRepository.save(employee);
}
答案 0 :(得分:2)
@Entity
public class Employee {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "servedBy")
private List<Orders> orders;
}
mappedBy
在这里意味着servedBy
中的Orders
用于维护Employee
和Order
之间的关系,这意味着Hibernate将基于以下内容更新外键:这个领域。您必须在servedBy
中设置Order
的值来指定关系,而不是在orders
中使用Employee
:
public void orderServed(Long employeeId, Long orderId) {
Orders order = orderRepository.findOne(orderId);
Employee employee = employeeRepository.findOne(employeeId);
//Set the forign key
order.setServedBy(employee);
employeeRepository.save(employee);
}
BTW,@OneToMany
已经允许配置级联行为。无需使用hibernate的@Cascade
:
@Entity
public class Employee {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "servedBy" , cascade={CascadeType.ALL})
private List<Orders> orders;
}