JSON 中的数据对象未按预期显示

时间:2021-01-16 12:54:04

标签: java mysql sql json spring

我在一个数据库中有两个表。一个是订单,另一个是产品。

这是一个类订单

@ManyToMany(cascade = CascadeType.ALL, mappedBy = "orders", fetch = FetchType.LAZY)
private Set<Product> products;

这是一个产品

@JsonIgnore
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "orders_products",
        joinColumns = { @JoinColumn(name = "product_id", nullable = false, updatable = false)},
        inverseJoinColumns = { @JoinColumn(name = "order_id", nullable = false, updatable = false)})
private Set<Order> orders;

当我向 REST API 发送请求以将 Product 添加到 Order 时:

<块引用>

localhost:8080/order/1/add/products?ids=1

我会得到预期的结果:

[
{
    "id": 1,
    "description": "Order number one description",
    "name": "Shopping cart for mobiles",
    "surcharge": 20.0,
    "products": [
        {
            "id": 1,
            "description": "Samsung S9",
            "price": 599.99
        }
    ]
}

]

毕竟当我发送 GET 请求以获取所有订单时:

<块引用>

本地主机:8080/订单

我会得到这个结果:

[
{
    "id": 1,
    "description": "Order number one description",
    "name": "Shopping cart for mobiles",
    "surcharge": 20.0,
    "products": []
}

]

我想打开“产品”以查看实际产品。为什么“产品”是空的或者不显示“产品”的正文。

谢谢。

更新:

它不会保留在数据库中,在表 orders_products 下。签入 @JoinTable( name = ...) 中的 Product 类。

如果我执行以下操作:

<块引用>

从产品中选择*;

# product_id    description price
1   Samsung S9  599.99
2   Notebook S9 1000.99
3   Headset 1000.99
4   Mone    45.99
<块引用>

从订单中选择*;

# order_id  description name    surcharge   user_id
1   Order number one description    Shopping cart for mobiles   20  2
2   Order for notebooks test second 20  2

但是如果我这样做。 应该有从 order_id 指向某些 product_id 的 ID。 因为@k-wasilewski 是数据不会持久化在数据库中。

<块引用>

select * from orders_products;

# product_id, order_id
   null        null

根据@Turing85 的要求,我添加了 OrderService 类中的一些代码。

    public List<Order> mapProductsToOrderById(final Long id, List<Long> ids) {
    Order order = orderRepository.findById(id).orElseThrow(
            () -> new OrderNotFoundException("Order with id: " + id + " was not found."));

    List<Product> products = productRepository.findAll();
    Set<Product> resultSet = order.getProducts();
    
    ids.forEach(x -> products.forEach(product -> {
        if(product.getId().compareTo(x) == 0){
            resultSet.add(productRepository.findById(x).orElseThrow(
                    () -> new ProductNotFoundException("Product with id: " + x + " was not found.")
            ));
            order.setProducts(resultSet);
            orderRepository.save(order);
        }
    }));
    return orderRepository.findAll();
}

有来自Controller类的方法。

    @GetMapping("{id}/add/products")
    public List<Order> mapProductsToOrder(@PathVariable Long id, @RequestParam("ids") List<Long> ids) {
    return orderService.mapProductsToOrderById(id, ids);
}

1 个答案:

答案 0 :(得分:1)

将方法 mapProductsToOrderById 移动到 ProductService.class。 并通过反向添加产品按顺序执行相同的操作。因此,您将订单添加到产品集中。