我有2个实体类 - Order和OrderDetail。以下是这两个类的代码片段。
@Entity
@Table(name="orders")
@IdClass(OrderPK.class)
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Id
private String customerEmail;
@Column(name="advance_order_time")
private Date advanceOrderTime;
@Column(name="amount")
private float amount;
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private Set<OrderDetail> orderDetailList;
public void addOrderDetail(OrderDetail orderDetail) {
if (orderDetail != null) {
if (orderDetailList == null) {`enter code here`
orderDetailList = new HashSet<OrderDetail>();
}
orderDetailList.add(orderDetail);
orderDetail.setOrder(this);
}
}
}
@Entity
@Table(name="order_details")
public class OrderDetail implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name="item_code")
private String itemCode;
@ManyToOne
@MapsId("id")
private Order order;
}
public class OrderPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
private int id;
@Column(name="customer_email")
private String customerEmail;
}
Order对象和OrderDetail对象的集合在数据库中成功插入,但OrderDetail的order_id列在null中。以下是代码段。
entityManager.persist(kfcOrder);
订单表具有复合键ID和customer_email。此id是列order_id的表order_details的外键。
请建议解决方法,以便在order_details表的数据库order_id中保存订单对象时也会保存。
答案 0 :(得分:0)
试试这个..
@ManyToOne(optional = false)
@JoinColumns({
@JoinColumn(name = "ORDER_ID",referencedColumnName = "id"),
@JoinColumn(name = "EMAIL",referencedColumnName = "customerEmail")
})
@MapsId("id")
private Order order;
如果父项不存在, optional = false
将确保不存在子项。