gpt4 book ai didi

java - JPA级联不插入外键

转载 作者:行者123 更新时间:2023-11-30 22:13:20 25 4
gpt4 key购买 nike

我有 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 列为空。下面是代码片段。

entityManager.persist(kfcOrder);

order 表有一个组合键 id 和 customer_email。此 id 是表 order_details 列 order_id 的外键。

请提出解决方法,以便在将订单对象持久保存在 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 将确保如果父项不存在则子项不能存在。

关于java - JPA级联不插入外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39289727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com