0

春季启动 2.2

@Entity
public class Cart {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @OneToOne(fetch = FetchType.EAGER,
            cascade = CascadeType.ALL,
            mappedBy = "cart")
    private Orders orders;
    @ElementCollection
    @CollectionTable(name = "cart_products", joinColumns = @JoinColumn(name = "cart_id"))
    @MapKeyJoinColumn(name = "product_id")
    @Column(name = "product_qantity")
private Map<Product, Integer> productsMap;


@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @NotNull
    @NotNull
    private String currency;
    @ElementCollection
    private Set<String> images;


@PostMapping("/cart/product")
    public Response addProduct(@RequestBody Map<String, Object> payloadMap) {
        logger.info("addProduct: payloadMap: " + payloadMap);
        String userName = payloadMap.get("user_name").toString();
        final Product product = new ObjectMapper().convertValue(payloadMap.get("product"), Product.class);
        int quantity = (int) payloadMap.get("quantity");
        Cart findCart = cartRepository.findByUsername(userName);
        if (findCart == null) {
            Cart cart = new Cart();
            cart.setCreated(new Date());
            cart.setUsername(userName);
            cart.addProducts(product, quantity);
            logger.info("addProduct: before_save_new_cart: " + cart);
            cartRepository.save(cart);
            logger.info("addProduct: success_add_product_to_new_cart: " + cart);
            return ResponseService.getSuccessResponse(GsonUtil.gson.toJson(cart));
        } else {
            findCart.addProducts(product, quantity);
            logger.info("addProduct: before_save_exist_cart: " + findCart);
            cartRepository.save(findCart);
            logger.info("addProduct: success_add_product_to_exist_cart: " + findCart);
            return ResponseService.getSuccessResponse(GsonUtil.gson.toJson(findCart));
        }
    }

这里发布请求:

POST .../cart/product

{
  "user_name": "admin@admin.com",
  "product": {
    "name": "product name",
    "description": "product description",
    "price": 10.15,
    "currency": "USD",
    "images": [
      "http://www.gravatar.com/avatar/11111?s=200x200&d=identicon",
      "http://www.gravatar.com/avatar/22222?s=200x200&d=identicon"
    ]
  },
  "quantity": 2

但我在这一行得到错误:

cartRepository.save(findCart);

错误:

2020-04-09 23:32:47.429  INFO 6130 --- [nio-8092-exec-1] r.o.s.e.controllers.CartController       : addProduct: payloadMap: {user_name=admin@admin.com, product={name=product name, description=product description, price=10.15, currency=USD, images=[http://www.gravatar.com/avatar/11111?s=200x200&d=identicon, http://www.gravatar.com/avatar/22222?s=200x200&d=identicon]}, quantity=2}
2020-04-09 23:32:47.564  INFO 6130 --- [nio-8092-exec-1] r.o.s.e.controllers.CartController       : addProduct: before_save_exist_cart: Cart{id=3, created=2020-04-08 20:55:13.98, updated=2020-04-08 20:55:36.334, username='admin@admin.com', orders=null, products={Product{id=0, name='product name', description='product description', created=null, updated=null, price=10.15, currency='USD', images=[http://www.gravatar.com/avatar/22222?s=200x200&d=identicon, http://www.gravatar.com/avatar/11111?s=200x200&d=identicon]}=2}}
2020-04-09 23:32:47.583  INFO 6130 --- [nio-8092-exec-1] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
2020-04-09 23:32:47.590 ERROR 6130 --- [nio-8092-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/api/v1] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.myproject_orders.api.model.Product; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.myproject_orders.api.model.Product] with root cause

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.myproject_orders.api.model.Product
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:347) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:495) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.persister.collection.AbstractCollectionPersister.writeIndex(AbstractCollectionPersister.java:940) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1588) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:89) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.13.Final.jar:5.4.13.Final]
4

0 回答 0