我有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对象保留在order_details表的数据库order_id中的同时也将其保存。
最佳答案
尝试这个..
@ManyToOne(optional = false)
@JoinColumns({
@JoinColumn(name = "ORDER_ID",referencedColumnName = "id"),
@JoinColumn(name = "EMAIL",referencedColumnName = "customerEmail")
})
@MapsId("id")
private Order order;
optional = false
将确保如果父代不存在,则子代将不存在。