这是父对象:
@Entity
@Table(name="cart")
public class Cart implements Serializable{
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@Column(name="id")
private Integer id;
@OneToMany(mappedBy="cart", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CartItem> cartItems;
...
}
这是子对象:
@Entity
@Table(name="cart_item")
public class CartItem implements Serializable{
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@Column(name="id")
private Integer id;
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
@JsonIgnore
private Cart cart;
...
}
使用此数据库图像,您可以看到字段CartItem.cart
具有表购物车的外键。
保存父对象时,我也要保存其子对象。
子对象在保存之前需要了解父对象的 id (您可以在CartItem类中看到@JoinColumn(name="cart_id")
)。我想框架可以解决 id 问题。
我得到了错误:
SEVERE: Servlet.service() for servlet [dispatcher] in context with
path [/webstore] threw exception [Request processing failed; nested
exception is java.lang.IllegalStateException:
org.hibernate.TransientObjectException: object references an unsaved
transient instance - save the transient instance before flushing:
com.depasmatte.webstore.domain.Cart] with root cause
org.hibernate.TransientObjectException: object references an unsaved
transient instance - save the transient instance before flushing:
com.depasmatte.webstore.domain.Cart
我应该如何处理这样的问题?
打个伙计