I’m having an issue with a List(or set I tried both) in my ecommerce website where I try to add a List of Jewelry(called CartJewelry in my code) that are in the Cart entity to the Order entity and I keep getting this error Caused by: org.hibernate.HibernateException: Found shared references to a collection: com.batavia.ecommerce.model.ClientOrder.cartJewelryItems
. I know it’s specifically that list cause when I don’t pass it to the order entity it saves without an issue.
This is my “CartJewelry” entity
@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
public class CartJewelry {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "jewelry_id")
private Jewelry jewelry;
@JsonIgnore
@ManyToMany(mappedBy = "cartJewelry")
private List<Cart> carts;
@JsonIgnore
@ManyToMany(mappedBy = "cartJewelryItems")
private List<ClientOrder> orders;
private int quantityInOrder;
public CartJewelry(Long id, Jewelry jewelry, int quantityInOrder) {
this.id = id;
this.jewelry = jewelry;
this.quantityInOrder = quantityInOrder;
}
public CartJewelry(Jewelry jewelry, int quantityInOrder) {
this.jewelry = jewelry;
this.quantityInOrder = quantityInOrder;
}
}
This is my ClientOrder entity:
@Entity
@Getter
@Setter
@NoArgsConstructor
public class ClientOrder {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonManagedReference
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "jewelryInOrder",
joinColumns = @JoinColumn(name = "cartJewelry_id"),
inverseJoinColumns = @JoinColumn(name = "order_id")
)
private List<CartJewelry> cartJewelryItems;
@ManyToOne
@JoinColumn(name = "client_id")
private User client;
@Column(name = "total_price")
private int totalPrice;
@Column(name = "date_ordered")
private Date dateOrdered;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "billing_address_id", referencedColumnName = "id")
private BillingAddress billingAddress;
public ClientOrder(List<CartJewelry> cartJewelryItems, User client, int totalPrice, Date dateOrdered, BillingAddress billingAddress) {
this.cartJewelryItems = cartJewelryItems;
this.client = client;
this.totalPrice = totalPrice;
this.dateOrdered = dateOrdered;
this.billingAddress = billingAddress;
}
public ClientOrder(List<CartJewelry> cartJewelryItems, int totalPrice, Date dateOrdered) {
this.cartJewelryItems = cartJewelryItems;
this.totalPrice = totalPrice;
this.dateOrdered = dateOrdered;
}
}
and my cart Entity from where we get the list of “CartJewelry” to give to the Order entity:
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonManagedReference
@ManyToMany
@JoinTable(
name = "jewelryInCart",
joinColumns = @JoinColumn(name = "cartJewelry_id"),
inverseJoinColumns = @JoinColumn(name = "cart_id")
)
private List<CartJewelry> cartJewelry;
@Column(name = "sub_total")
private int subTotal;
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
public Cart(Long id, List<CartJewelry> cartJewelry, int subTotal) {
this.id = id;
this.cartJewelry = cartJewelry;
this.subTotal = subTotal;
}
}
the controller that does the whole process:
@PostMapping("/process-order")
public ResponseEntity<String> processOrder(@ModelAttribute("billingAddress") BillingAddress billingAddress, @RequestParam("addressPartOne") String addOne, @RequestParam("addressPartTwo") String addTwo
, @RequestParam("addressPartThree") String addThree, @RequestParam("addressPartFour") String addFour, RedirectAttributes redirectAttributes){
billingAddress.setAddress(addOne + ", " + addThree + ", " + addTwo + ", " + addFour);
Cart cart = new Cart();
ClientOrder order = new ClientOrder();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
LocalDateTime currentDateTime = LocalDateTime.now();
Date currentDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
if (auth != null && auth.isAuthenticated()){
Object principal = auth.getPrincipal();
UserDetails currentUser = (UserDetails) principal;
String email = currentUser.getUsername();
User userFound = userService.findByEmail(email);
cart = cartService.getCart(userFound);
List<CartJewelry> jewelryInCart = cart.getCartJewelry();
try {
billingAddressService.saveBillingAddress(billingAddress);
System.out.println("Address saved in db!");
order.setBillingAddress(billingAddress);
order.setClient(userFound);
order.setCartJewelryItems(jewelryInCart);
order.setTotalPrice(cart.getSubTotal());
order.setDateOrdered(currentDate);
System.out.println(jewelryInCart);
// System.out.println("Cart cleared!");
orderService.makeOrder(order);
cartService.removeFromCart(cart);
System.out.println("Order made!");
redirectAttributes.addFlashAttribute("Message", "Registration successful! Please log in to continue.");
return ResponseEntity.status(HttpStatus.FOUND).header("Location", "/browse?success").build();
} catch (Exception e) {
e.printStackTrace();
}
}
redirectAttributes.addAttribute("errorMessage", "Registration failed. Please try again.");
return ResponseEntity.status(HttpStatus.FOUND).header("Location", "/check-out?fail").build();
}
Please, any help to resolve this would be great!
I tried changing it from a Set to a List, edited my relationships to see if it would fix it.
Even tried to feed the collection to a List before passing it to the ClientOrder object, it did not work.
Tried deleting the cart’s list before saving the ClientOrder one but that just gave me another error:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection: could not initialize proxy – no Session
Bapu Batavia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.