繁体   English   中英

org.hibernate.PersistentObjectException:传递给持久化 OrderProduct 的分离实体

[英]org.hibernate.PersistentObjectException: detached entity passed to persist OrderProduct

我正在学习微服务,在创建数据库条目时遇到了这个错误。

org.hibernate.PersistentObjectException:传递给持久化的分离实体:OrderProduct

当我将级联更改为 MERGE 时,数据仅保存在 OrderDetail 表中。 我已经搜索过但找不到任何有用的东西。 这是我的代码。

Feign代理接口:

@FeignClient(name="product-metadata",url="localhost:8080")
public interface OrderProductProxy {
    @GetMapping("/products/productdetails/{productId}")
    public OrderProduct getProductDetails(@PathVariable UUID productId);
}

OrderDetail 实体:

@Getter @Setter
@NoArgsConstructor @AllArgsConstructor
@Entity
public class OrderDetail {
    
    @Id
    @GeneratedValue
    private long id;
    
    
    private UUID orderId;
    
    private String customerId;
    
    private String totalAmount;
    
    @OneToMany(cascade = CascadeType.ALL,mappedBy = "orderId")
    private List<OrderProduct> productId;

    public void addProduct(OrderProduct orderProduct) {
        if(orderProduct != null) {
            if(productId == null) {
                productId = new ArrayList<>();
            }
        }
        this.productId.add(orderProduct);
        orderProduct.setOrderId(this);
    }
}

订单产品实体:

@Getter @Setter
@NoArgsConstructor @AllArgsConstructor
@ToString
@Entity
public class OrderProduct {
    
    
    private long id;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private UUID uniqueId;
    private String name;
    private BigDecimal price;
    
    @ManyToOne
    @JoinColumn(name="orderId")
    private OrderDetail orderId;
}

Controller:

@PostMapping("/create/{productId}")
    public OrderDetail createOrder(@PathVariable UUID productId,@RequestBody OrderDetail orderDetails) {
        
        OrderProduct orderProduct = proxy.getProductDetails(productId);
        System.out.println(orderProduct);
        orderDetails.addProduct(orderProduct);
        UUID orderId = UUID.randomUUID();
        orderDetails.setOrderId(orderId);
        return repo.save(orderDetails);
    }

尝试使用@Transactional注释您的方法。 然后OrderProduct将不会在createOrder方法中分离。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM