Hibernate Found shared references to a collection error

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

New contributor

Bapu Batavia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật