Почему CascadeType.MERGE, CascadeType.PERSIST не помогают получить внутренние данные - PullRequest
0 голосов
/ 27 апреля 2020

Spring boot 2

@Entity
public class Cart {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private int id;
    @NotNull
    private String cartId;
    @NotNull
    private String username;
    @NotNull
    @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
    private Date created;
    @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
    private Date updated;
    @OneToMany(mappedBy = "cart", fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST}, orphanRemoval = true)
    private Set<ProductEntry> productEntities = new HashSet<>();


@Entity
public class ProductEntry {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Exclude
    private int id;
    @NotNull
    @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
    @Exclude
    private Date created;
    @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
    @Exclude
    private Date updated;
    private int quantity;
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Product product;
    @Exclude
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    private Orders orders;
    @Exclude
    @JsonIgnore
    @ManyToOne(fetch = FetchType.EAGER)
    private Cart cart;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Exclude
    private int id;
    @NotNull
    private String productId;
    @NotNull
    private String name;
    private String description;
    @NotNull
    @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
    private Date created;
    @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
    private Date updated;
    @NotNull
    private double price;
    @NotNull
    private String currency;
    @ElementCollection
    private Set<String> images;
    @Exclude
    @JsonIgnore
    @OneToOne(mappedBy = "product", fetch = FetchType.EAGER)
    private ProductEntry productEntry;

Контроллер:

 // Add product to cart
    @PostMapping(value = "/productEntry")
    public String submitProductEntry(ProductEntry productEntry, Model model) {
        try {
            if (productEntry.getId() == 0) { // add productEntry
                logger.info("submitProductEntry: add_productEntry");
                Product product = productEntry.getProduct();
                product.setProductId(UUID.randomUUID().toString());
                product.setCreated(new Date());
                productEntry.setProduct(product);
                productEntry.setCreated(product.getCreated());
            } else { // update productEntry
                logger.info("submitProductEntry: update_productEntry");
                Product product = productEntry.getProduct();
                product.setUpdated(new Date());
                productEntry.setUpdated(product.getUpdated());
            }
            Cart cart = cartService.addProductToCart(productEntry);
            logger.info("submitProductEntry: success_return_cart_from_response\n " + cart);
            // When you do save on entity with empty id it will do a save(insert).
            // When you do save on entity with existing id it will do an update.
            // The save() method returns the saved entity, including the updated id field.
            Cart findLocalCart = cartRepository.findByUsername(currentUser.getUsername());
            logger.info("submitProductEntry: userName = " + currentUser.getUsername() + " -> findLocalCart:\n" + findLocalCart);
            if (findLocalCart != null) {
                logger.info("submitProductEntry: already_exist_Localcart -> update_Localcart");
                cart.setId(findLocalCart.getId());
            }
            cart = cartRepository.save(cart);
            logger.info("submitProductEntry: success_saved_cart_to_db:\n" + cart);
            return "redirect:/cart";
        } catch (Exception ex) {
            logger.error("submitProductEntry: Error = " + ex.getMessage(), ex);
            model.addAttribute("addProductError", ex.getMessage());
            return "productEntry.html";
        }
    }

здесь журнал:

CartController - submitProductEntry: success_saved_cart_to_db:
Cart {id = 2, cartId = 66b989d1-7c5c-4c23-8e8d-81c1baac5e1d, username = admin@admin.com, productEntities(1)
[
ProductEntity {id = 3, created = Mon Apr 27 18:59:33 EEST 2020, updated = null, quantity = 1, product = Product {id = 4, productId = 0eeb624b-0603-4ba6-85bd-afae26c914ee, name = 'My product 1', description='', created=Mon Apr 27 18:59:33 EEST 2020, updated=null, price=1.0, currency='USD', images=[url_1]}}], created = Mon Apr 27 18:59:33 EEST 2020, updated = null}

Как видите размер productEntities = 1

Ницца. Это правильно.

Но вот метод возврата содержимого корзины:

 @GetMapping("/cart")
    public String getCartDetails(Model model) {
        currentUser = userRepository.findByUsername(UserService.getCurrentUserName());
        logger.info("getCartDetails: finding_cart_by_userName = " + currentUser);
        Cart findLocalCart = cartRepository.findByUsername(currentUser.getUsername());
        logger.info("getCartDetails: findLocalCart:\n" + findLocalCart);
        Set<ProductEntry> productEntities = new HashSet<>();
        if (findLocalCart != null) {
            productEntities = findLocalCart.getProductEntities();
        }
        model.addAttribute("productEntities", productEntities);
        model.addAttribute("appName", appName);
        return "cart";
    }

и вот лог:

CartController - getCartDetails: findLocalCart:
Cart {id = 2, cartId = 66b989d1-7c5c-4c23-8e8d-81c1baac5e1d, username = admin@admin.com, productEntities(0)
[], created = 2020-04-27 18:59:33.0, updated = null}

Как видите размер productEntities - 0

Почему?

Здесь весь журнал:

[INFO ] 2020-04-27 21:59:25.684 [http-nio-8090-exec-7] CartController - addProduct
[INFO ] 2020-04-27 21:59:33.690 [http-nio-8090-exec-9] CartController - submitProductEntry: add_productEntry
[INFO ] 2020-04-27 21:59:33.690 [http-nio-8090-exec-9] CartController - addProductToCart: 
ProductEntity {id = 0, created = Mon Apr 27 21:59:33 EEST 2020, updated = null, quantity = 1, product = Product {id = 0, productId = 0eeb624b-0603-4ba6-85bd-afae26c914ee, name = 'My product 1', description='', created=Mon Apr 27 21:59:33 EEST 2020, updated=null, price=1.0, currency='USD', images=[url_1]}}
[INFO ] 2020-04-27 21:59:33.826 [http-nio-8090-exec-9] TransportService - INIT: 
[INFO ] 2020-04-27 21:59:33.834 [http-nio-8090-exec-9] TransportService - addProductToCart: json = {"user_name":"admin@admin.com","product":"{\"productId\":\"0eeb624b-0603-4ba6-85bd-afae26c914ee\",\"name\":\"My product 1\",\"description\":\"\",\"created\":\"Apr 27, 2020, 9:59:33 PM\",\"price\":1.0,\"currency\":\"USD\",\"images\":[\"url_1\"]}","quantity":1}
[INFO ] 2020-04-27 21:59:33.851 [http-nio-8090-exec-9] OkHttpClient - --> POST http://127.0.0.1:8092/api/v1/cart/product http/1.1
[INFO ] 2020-04-27 21:59:33.851 [http-nio-8090-exec-9] OkHttpClient - Content-Type: application/json; charset=UTF-8
[INFO ] 2020-04-27 21:59:33.852 [http-nio-8090-exec-9] OkHttpClient - Content-Length: 259
[INFO ] 2020-04-27 21:59:33.852 [http-nio-8090-exec-9] OkHttpClient - 
[INFO ] 2020-04-27 21:59:33.852 [http-nio-8090-exec-9] OkHttpClient - {"user_name":"admin@admin.com","product":"{\"productId\":\"0eeb624b-0603-4ba6-85bd-afae26c914ee\",\"name\":\"My product 1\",\"description\":\"\",\"created\":\"Apr 27, 2020, 9:59:33 PM\",\"price\":1.0,\"currency\":\"USD\",\"images\":[\"url_1\"]}","quantity":1}
[INFO ] 2020-04-27 21:59:33.852 [http-nio-8090-exec-9] OkHttpClient - --> END POST (259-byte body)
[INFO ] 2020-04-27 21:59:34.027 [http-nio-8090-exec-9] OkHttpClient - <-- 200  http://127.0.0.1:8092/api/v1/cart/product (174ms)
[INFO ] 2020-04-27 21:59:34.027 [http-nio-8090-exec-9] OkHttpClient - Content-Type: application/json
[INFO ] 2020-04-27 21:59:34.027 [http-nio-8090-exec-9] OkHttpClient - Transfer-Encoding: chunked
[INFO ] 2020-04-27 21:59:34.027 [http-nio-8090-exec-9] OkHttpClient - Date: Mon, 27 Apr 2020 18:59:34 GMT
[INFO ] 2020-04-27 21:59:34.027 [http-nio-8090-exec-9] OkHttpClient - Keep-Alive: timeout=60
[INFO ] 2020-04-27 21:59:34.028 [http-nio-8090-exec-9] OkHttpClient - Connection: keep-alive
[INFO ] 2020-04-27 21:59:34.028 [http-nio-8090-exec-9] OkHttpClient - 
[INFO ] 2020-04-27 21:59:34.028 [http-nio-8090-exec-9] OkHttpClient - {"cartId":"66b989d1-7c5c-4c23-8e8d-81c1baac5e1d","username":"admin@admin.com","created":"2020-04-27T18:59:33.971+00:00","updated":null,"productEntities":[{"created":"2020-04-27T18:59:33.971+00:00","updated":null,"quantity":1,"product":{"productId":"0eeb624b-0603-4ba6-85bd-afae26c914ee","name":"My product 1","description":"","created":"2020-04-27T18:59:33.000+00:00","updated":null,"price":1.0,"currency":"USD","images":["url_1"]}}],"currency":"USD","totalAmount":1.0}
[INFO ] 2020-04-27 21:59:34.028 [http-nio-8090-exec-9] OkHttpClient - <-- END HTTP (469-byte body)
[INFO ] 2020-04-27 21:59:34.030 [http-nio-8090-exec-9] CartController - submitProductEntry: success_return_cart_from_response
 Cart {id = 0, cartId = 66b989d1-7c5c-4c23-8e8d-81c1baac5e1d, username = admin@admin.com, productEntities(1)
[
ProductEntity {id = 0, created = Mon Apr 27 18:59:33 EEST 2020, updated = null, quantity = 1, product = Product {id = 0, productId = 0eeb624b-0603-4ba6-85bd-afae26c914ee, name = 'My product 1', description='', created=Mon Apr 27 18:59:33 EEST 2020, updated=null, price=1.0, currency='USD', images=[url_1]}}], created = Mon Apr 27 18:59:33 EEST 2020, updated = null}
[DEBUG] 2020-04-27 21:59:34.030 [http-nio-8090-exec-9] SQL - select cart0_.id as id1_0_, cart0_.cart_id as cart_id2_0_, cart0_.created as created3_0_, cart0_.updated as updated4_0_, cart0_.username as username5_0_ from cart cart0_ where cart0_.username=?
[INFO ] 2020-04-27 21:59:34.031 [http-nio-8090-exec-9] CartController - submitProductEntry: userName = admin@admin.com -> findLocalCart:
null
[DEBUG] 2020-04-27 21:59:34.033 [http-nio-8090-exec-9] SQL - call next value for hibernate_sequence
[DEBUG] 2020-04-27 21:59:34.034 [http-nio-8090-exec-9] SQL - call next value for hibernate_sequence
[DEBUG] 2020-04-27 21:59:34.034 [http-nio-8090-exec-9] SQL - call next value for hibernate_sequence
[DEBUG] 2020-04-27 21:59:34.035 [http-nio-8090-exec-9] SQL - insert into cart (cart_id, created, updated, username, id) values (?, ?, ?, ?, ?)
[DEBUG] 2020-04-27 21:59:34.036 [http-nio-8090-exec-9] SQL - insert into product (created, currency, description, name, price, product_id, updated, id) values (?, ?, ?, ?, ?, ?, ?, ?)
[DEBUG] 2020-04-27 21:59:34.036 [http-nio-8090-exec-9] SQL - insert into product_entry (cart_id, created, orders_id, product_id, quantity, updated, id) values (?, ?, ?, ?, ?, ?, ?)
[DEBUG] 2020-04-27 21:59:34.037 [http-nio-8090-exec-9] SQL - insert into product_images (product_id, images) values (?, ?)
[INFO ] 2020-04-27 21:59:34.038 [http-nio-8090-exec-9] CartController - submitProductEntry: success_saved_cart_to_db:
Cart {id = 2, cartId = 66b989d1-7c5c-4c23-8e8d-81c1baac5e1d, username = admin@admin.com, productEntities(1)
[
ProductEntity {id = 3, created = Mon Apr 27 18:59:33 EEST 2020, updated = null, quantity = 1, product = Product {id = 4, productId = 0eeb624b-0603-4ba6-85bd-afae26c914ee, name = 'My product 1', description='', created=Mon Apr 27 18:59:33 EEST 2020, updated=null, price=1.0, currency='USD', images=[url_1]}}], created = Mon Apr 27 18:59:33 EEST 2020, updated = null}
[DEBUG] 2020-04-27 21:59:34.045 [http-nio-8090-exec-10] SQL - select user0_.id as id1_7_, user0_.active as active2_7_, user0_.created as created3_7_, user0_.password as password4_7_, user0_.updated as updated5_7_, user0_.username as username6_7_ from usr user0_ where user0_.username=?
[DEBUG] 2020-04-27 21:59:34.045 [http-nio-8090-exec-10] SQL - select roles0_.user_id as user_id1_6_0_, roles0_.role as role2_6_0_ from user_roles roles0_ where roles0_.user_id=?
[DEBUG] 2020-04-27 21:59:34.046 [http-nio-8090-exec-10] SQL - select orders0_.user_id as user_id7_2_0_, orders0_.id as id1_2_0_, orders0_.id as id1_2_1_, orders0_.category_id as category6_2_1_, orders0_.created as created2_2_1_, orders0_.description as descript3_2_1_, orders0_.name as name4_2_1_, orders0_.updated as updated5_2_1_, orders0_.user_id as user_id7_2_1_ from orders orders0_ where orders0_.user_id=?
[INFO ] 2020-04-27 21:59:34.046 [http-nio-8090-exec-10] CartController - getCartDetails: finding_cart_by_userName = 
User{id=1, username='admin@admin.com', password='admin@admin.com', active=true, roles=[ADMIN], created=2020-04-27 21:58:51.521, updated=null}
[DEBUG] 2020-04-27 21:59:34.046 [http-nio-8090-exec-10] SQL - select cart0_.id as id1_0_, cart0_.cart_id as cart_id2_0_, cart0_.created as created3_0_, cart0_.updated as updated4_0_, cart0_.username as username5_0_ from cart cart0_ where cart0_.username=?
[DEBUG] 2020-04-27 21:59:34.047 [http-nio-8090-exec-10] SQL - select productent0_.cart_id as cart_id5_5_0_, productent0_.id as id1_5_0_, productent0_.id as id1_5_1_, productent0_.cart_id as cart_id5_5_1_, productent0_.created as created2_5_1_, productent0_.orders_id as orders_i6_5_1_, productent0_.product_id as product_7_5_1_, productent0_.quantity as quantity3_5_1_, productent0_.updated as updated4_5_1_, product1_.id as id1_3_2_, product1_.created as created2_3_2_, product1_.currency as currency3_3_2_, product1_.description as descript4_3_2_, product1_.name as name5_3_2_, product1_.price as price6_3_2_, product1_.product_id as product_7_3_2_, product1_.updated as updated8_3_2_ from product_entry productent0_ left outer join product product1_ on productent0_.product_id=product1_.id where productent0_.cart_id=?
[INFO ] 2020-04-27 21:59:34.048 [http-nio-8090-exec-10] CartController - getCartDetails: findLocalCart:
Cart {id = 2, cartId = 66b989d1-7c5c-4c23-8e8d-81c1baac5e1d, username = admin@admin.com, productEntities(0)
[], created = 2020-04-27 18:59:33.0, updated = null}

PS Как видите, я использую аннотации, но это не помогает

cascade = {CascadeType.MERGE, CascadeType.PERSIST}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...