【问题标题】:One to Many relation in jpa, always null in foreign keyjpa中的一对多关系,外键始终为空
【发布时间】:2017-08-02 19:32:56
【问题描述】:

我在 hibernate jpa 中的关系有一些问题。我想建立 OneToMany 关系,但是当我将对象“one”保存在 base 中时,表中的“many”列中包含的外键始终为空。 就我而言,我有 Customer 类:

@OneToOne(fetch=FetchType.LAZY, mappedBy="customer", cascade = CascadeType.ALL)
private Address billingAddress;
@Column(name="phone_address")
private String phoneNumber;
@OneToMany(fetch=FetchType.EAGER, mappedBy="customer")
private List<Order> orders;

它包含与 Order 的 OneToMany 关系(完美运行)。 订单类:

@Id
@GeneratedValue
@Column(name="order_id")
private Long orderId;
@OneToOne(fetch=FetchType.LAZY, mappedBy="order", cascade = CascadeType.ALL)
private Cart cart;
@ManyToOne
@JoinColumn(name="customer_id")
private Customer customer;
@OneToOne(fetch=FetchType.LAZY, mappedBy="order", cascade = CascadeType.MERGE)
private Address shippingDetail;

Order 类包含 Cart (OneToOne):

@Id
@GeneratedValue
@Column(name="base_id")
private Long baseId;
@Column(name="cart_id")
private String cartId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "cart", cascade = CascadeType.ALL)
@MapKeyColumn(name = "items_keys")
private Map<Long, CartItem> cartItems;
@Column(name="grand_total")
private BigDecimal grandTotal;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Order order;

这是 Cart 类中的 addCartItem 方法:

public void addCartItem(CartItem item){
    Long productId = item.getProduct().getProductId();

    if(cartItems.containsKey(productId)){
        CartItem existingCartItem = cartItems.get(productId);
        existingCartItem.setQuantity(existingCartItem.getQuantity() + item.getQuantity());
        cartItems.put(productId, existingCartItem);
    }else{
        cartItems.put(productId, item);
        //item.setCart(this);
    }
    updateGrandTotal();
}

在这里,Cart 必须在 OneToMany 关系中包含 CartItem 映射,这不起作用。 CartItem 类:

@Id
@GeneratedValue
private long id;
@OneToOne(fetch=FetchType.LAZY, mappedBy="cartItem", cascade = CascadeType.MERGE)
private Product product;
private int quantity;
private BigDecimal totalPrice;
@ManyToOne
private Cart cart;

据我所知,我需要在 CartItem 中启动外键,我尝试在 addCartItem 方法中执行此操作,但是当我这样做时,会出现 StackOverflowError。我是否错过了什么或如何使用 Cart 启动 CartItem

【问题讨论】:

  • 我知道我需要启动 CartItem,但是这行已经被注释的代码会导致 StackOverFlowError,就像我上面写的那样。
  • 我倾向于猜测其他地方存在问题。特别是,StackOverflowError 通常表示递归失控。您所提供的内容中没有任何线索可以说明为什么会发生这种情况。像往常一样,证明问题的minimal reproducible example 将是有用且适当的。

标签: java spring hibernate jpa


【解决方案1】:

解决办法在这里:Json (fasterxml) stackoverflow exception

问题在于在 REST 控制器中解析我的实体,您需要使用 @JsonIgnore。这就是花费我这么多时间的全部 -.-

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多