对象引用未保存的瞬态实例-在刷新之前保存瞬态实例(JPA-Hibernate)

时间:2018-11-27 13:11:15

标签: database hibernate jpa orm

这是父对象:

@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具有表购物车的外键。

enter image description here

保存父对象时,我也要保存其子对象。

子对象在保存之前需要了解父对象的 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

我应该如何处理这样的问题?

打个伙计

0 个答案:

没有答案