[英]Hibernate One to Many relation- Child table not updating
Here I am adding a list of new orders to a specific user.在这里,我向特定用户添加新订单列表。 While adding orders to a specific user, it returns success status, but still my database is empty.
在向特定用户添加订单时,它返回成功状态,但我的数据库仍然是空的。 Why the data is not getting added...?
为什么没有添加数据...?
Users用户
@Entity
Class Users{
@Id
private int id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<Orders> orders;
}
Orders订单
@Entity
Class Orders{
@Id
private int id;
private Date orderDate;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
}
Repository存储库
public ResponseEntity<String> addOrder(int userId,List<Orders> orders) throws UserNotFound{
User user =userRepository.findById(userId).orElse(null);
if(user==null) throw new UserNotFound("User Not Found");
for(Orders o:orders){
o.setOrderDate(new Date("....."));
}
user.getOrders().addAll(orders);
userRepository.save(user);
} }
Try to add cascade persist to your relation specification:尝试将级联持久添加到您的关系规范中:
@Entity
Class Users{
@Id
private int id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade={CascadeType.PERSIST})
private List<Orders> orders;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.