I have some problem with relations in hibernate jpa. I'd like to make OneToMany relation but when i save object "one" in base then in table "many" column contains foreign key is always null. In my case i have class 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;
It contains OneToMany relation with Order (which works perfect). Order class:
@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 class contains 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;
Here is addCartItem method in Cart class:
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();
}
And here we are, Cart has to contain CartItem map in OneToMany relation which doesn't work. CartItem class:
@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;
As far as i know I need to initiate foreign key in CartItem, i tried to do it in addCartItem method but when i do so, there is StackOverflowError. Did I miss something or how to initiate CartItem with Cart?