我在一个数据库中有两个表。一个是订单另一个是产品。
这是班级秩序
@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发送请求以将产品添加到订单中时:
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请求以获取所有订单时:
localhost:8080/order
我将得到以下结果:
[
{
"id": 1,
"description": "Order number one description",
"name": "Shopping cart for mobiles",
"surcharge": 20.0,
"products": []
}
]
我希望“产品”是开放的,看到实际的产品。为什么“产品”是空的,或者它没有显示“产品”的主体。
谢谢您。
更新:
它不会在数据库中持久化,在表orders\U products下。签入@jointable中的产品类(name=…)。
如果我做了以下事情:
从产品中选择*;
# 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
但如果我这么做了。从订单id到某些产品id应该有id。因为@k-wasilewski was数据不会在数据库中持久存在。
从订单和产品中选择*;
# 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();
}
控制器类中没有方法。
@GetMapping("{id}/add/products")
public List<Order> mapProductsToOrder(@PathVariable Long id, @RequestParam("ids") List<Long> ids) {
return orderService.mapProductsToOrderById(id, ids);
}
1条答案
按热度按时间ni65a41a1#
将方法mapproductstoorderbyid移到productservice.class。和你做的一样,把产品添加到订单中。所以你把订单添加到产品集中。