我有两张桌子'订单'和' orderlines'并使用了双向OneToMany映射。当我保存订单时,记录已成功插入到表格中,但是我的排序' table为空。没有插入记录。
这是Controller中的保存操作代码。
@RequestMapping(value = "ordersuccess", method = RequestMethod.POST)
public String processOrder(@ModelAttribute("order") Order order,
@ModelAttribute("cart") Cart cart,
BindingResult result) {
if (!result.hasErrors()) {
Set<OrderLine> orderLines = new HashSet<OrderLine>();
for(CartLine c : cart.getCartLines()) {
OrderLine line = new OrderLine();
line.setOrder(order);
line.setProduct(c.getProduct());
line.setProductPrice(c.getProduct().getPrice());
line.setTotalPrice(c.getPrice());
orderLines.add(line);
order.setOrderLines(orderLines);
}
orderService.save(order);
orderLineService.save(orderLine);
}
return "ordersuccess";
}
有人能指出我在做什么错误。
修改: OrderLine.java
public class OrderLine {
@Id
@GeneratedValue
@Column(name="orderline_id")
private int orderline_id;
@ManyToOne
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(targetEntity = Product.class,
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
@JoinTable(
name="products",
joinColumns=@JoinColumn(name="product_id")
)
private Product product;
)
Order.java
public class Order {
@Id
@GeneratedValue
@Column(name="id")
private int id;
@OneToMany(mappedBy = "order")
private Set<OrderLine> orderLines;
//getter/setter
答案 0 :(得分:0)
创建了orderLines对象:
Set<OrderLine> orderLines = new HashSet<OrderLine>();
然后为其添加行:
orderLines.add(line);
但它从未归结为订单或发送到服务层。
OrderLine.product映射也应该像这样
public class OrderLine {
@Id
@GeneratedValue
@Column(name="orderline_id")
private int orderline_id;
@ManyToOne
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "product_id")
private Product product;
}
和Order.orderLines应该有一个级联:
public class Order {
@Id
@GeneratedValue
@Column(name="id")
private int id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private Set<OrderLine> orderLines;
}
然后您需要保存orderLines:
order.setOrderLines(orderLines);
并保存订单:
orderService.save(order);
保存订单时,它也会对订单线和相关产品进行级联。
如果您有双向关联,请不要忘记设置双方。