我正在做一个教师项目,我们正在使用JPA作为数据库。但是,我陷入了这种一对多的关系。我正在尝试通过引用多个GuestOrders和GuestOrders来引用Waiter,但到目前为止没有成功。
服务员拥有许多GuestOrders
许多GuestOrder属于一个服务员
服务员
@Entity
@Table(name = "waiter")
@PrimaryKeyJoinColumn(name = "USER_ID")
@DiscriminatorValue("W")
public class Waiter extends Worker {
@OneToMany(mappedBy="waiter", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<GuestOrder> activeGuestOrders;
public Waiter() {
this.activeGuestOrders = new ArrayList<>();
}
public Waiter(String email, String password, String name, String surname,
Date bithday, int shoeSize, int dressSize, Role role) {
super(email, password, name, surname, bithday, shoeSize, dressSize, role);
this.activeGuestOrders = new ArrayList<>();
}
public Collection<GuestOrder> getActiveGuestOrders() {
return activeGuestOrders;
}
public void setActiveGuestOrders(Collection<GuestOrder> guestOrders) {
this.activeGuestOrders = guestOrders;
}
public void addActiveOrder(String newOrder){
GuestOrder newOne = new GuestOrder(newOrder);
this.activeGuestOrders.add(newOne);
}
public void addActiveOrder(GuestOrder newGuestOrder){
this.activeGuestOrders.add(newGuestOrder);
}
}
GuestOrder
@Entity
public class GuestOrder {
@GeneratedValue
@Id
private long order_id;
@Column
private String orders;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private Waiter waiter;
public Waiter getWaiter() {
return waiter;
}
public void setWaiter(Waiter waiter) {
waiter = waiter;
}
public GuestOrder() {}
public GuestOrder(String name){
this.orders = name;
}
}
发生添加的部分代码:
Waiter newWork = new Waiter(email, password, name, surname, bithday, shoeSize, dressSize,new Role(role));
newWork.addActiveOrder("Order1");
newWork.addActiveOrder("Order2");
repository.flush();
return repository.save(newWork);
我最终的状态是:
GuestOrder Table
Waiter Table
*对不起,小图片。
我尝试了所有其他我设法通过google找到的解决方案,但并没有帮助我。
最佳答案
如果要使用级联,请在@OneToMany上进行此工作,则必须在关系的两侧设置依赖项:
Waiter newWork = new Waiter(email, password, name, surname, bithday, shoeSize, dressSize,new Role(role));
GuestOrder order1 = new GuestOrder();
GuestOrder order2 = new GuestOrder();
order1.setWaiter(newWork);
order2.setWaiter(newWork);
newWork.addActiveOrder(order1);
newWork.addActiveOrder(order2);
repository.flush();
return repository.save(newWork);
否则,持久性提供程序将不会将此关系视为已完全配置。