Это мой объект «CartJewelry»
Код: Выделить всё
@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 carts;
@JsonIgnore
@ManyToMany(mappedBy = "cartJewelryItems")
private List 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;
}
}
Код: Выделить всё
@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 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 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 cartJewelryItems, int totalPrice, Date dateOrdered) {
this.cartJewelryItems = cartJewelryItems;
this.totalPrice = totalPrice;
this.dateOrdered = dateOrdered;
}
}
Код: Выделить всё
@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;
@Column(name = "sub_total")
private int subTotal;
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
public Cart(Long id, List cartJewelry, int subTotal) {
this.id = id;
this.cartJewelry = cartJewelry;
this.subTotal = subTotal;
}
}
Код: Выделить всё
@PostMapping("/process-order")
public ResponseEntity 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 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();
}
Я попробовал изменить его с набора на список, отредактировал свои отношения, чтобы посмотреть, есть ли это исправило бы это.
Даже пытался передать коллекцию в список, прежде чем передавать ее объекту ClientOrder, это не сработало.
Пытался удалить список корзины перед сохранением списка ClientOrder, но это просто дало мне еще одна ошибка:
org.hibernate.LazyInitializationException: не удалось лениво инициализировать коллекцию: не удалось инициализировать прокси — нет сеанса
Подробнее здесь: https://stackoverflow.com/questions/784 ... tion-error
Мобильная версия