java 组织的休眠状态,持久对象异常:传递给持久化OrderProduct的分离实体

lf3rwulv  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(103)

我正在学习微服务,当我创建一个数据库条目时,我遇到了这个错误。
组织的休眠状态。持久对象异常:传递到持久化的分离实体:订单产品
当我改变级联合并然后数据只保存在OrderDetail表。我已经搜索,但没有找到任何有用的。这里是我的代码。
伪代理接口:

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

订单明细实体:

@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;
}

控制器:

@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);
    }
zu0ti5jz

zu0ti5jz1#

尝试用@Transactional注解你的方法,这样OrderProduct就不会在createOrder方法中被分离。

相关问题