订单与员工之间的JPA关系

时间:2019-02-23 15:29:45

标签: java mysql database hibernate jpa

我正在创建订单,后来又将员工分配给该订单。所以我很难在这两者之间建立联系。我的订单表没有更新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);
}

1 个答案:

答案 0 :(得分:2)

@Entity
public class Employee {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "servedBy")
    private List<Orders> orders;

} 

mappedBy在这里意味着servedBy中的Orders用于维护EmployeeOrder之间的关系,这意味着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;

}