【发布时间】:2022-01-05 21:22:19
【问题描述】:
我的 Spring Boot 应用程序中存在多对多关系。但是当我尝试得到响应时,我总是得到一个空数组; 这是我的类(我粘贴了没有构造函数、getter 和 setter 的代码,但我的代码中有它们):
@Entity
@Table(name="orders")
public class Order {
private @Id
@GeneratedValue
Long id;
@OneToOne(cascade = CascadeType.ALL)
private Customer customer;
@OneToMany(mappedBy = "product",fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH},orphanRemoval = true)
private Set<ProductOrderDetails> productOrderDetails;
@DateTimeFormat
private Date shippmentDate;
private double totalOrderPrice;
private OrderStatus status;
private String note1;
private String note2;
@Entity
@Table
public class Product {
private @Id
@GeneratedValue
Long id;
private String name;
private String model;
private String color;
private String material;
private double price;
@Transient
private int productQuantity;
@OneToMany(mappedBy = "order",fetch = FetchType.LAZY)
private List<ProductOrderDetails> productOrderDetailsSet;
@Entity
@IdClass(ProductOrderDetails.class)
public class ProductOrderDetails implements Serializable {
@Id
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="order_id")
Order order;
@Id
@ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH})
@JoinColumn(name="product_id")
Product product;
private int quantity;
这是我的 OrderController 代码:
@GetMapping("/{id}")
public Order One(@PathVariable Long id) {
Order order=repository.findById(id).orElseThrow(()->new ObjectNotFoundException(id));
return order;
}
这是我得到的回应:
{
"id": 2,
"customer": {
"id": 1,
"name": "Company",
"address": "Main Street 1",
"city": "Bern",
"state": "Switzerland",
"zip": 58529,
"contactPersonName": "John Smith",
"contactPersonEmail": "test@gmail.com"
},
"productOrderDetails": [],
"shippmentDate": "2020-12-09T23:00:00.000+00:00",
"totalOrderPrice": 3434.0,
"status": "WAITING",
"note1": "note 1",
"note2": "note 2"
}
如何获得 productOrderDetails 数组(订购的产品数组)? 如果我可以使用 JPA,我会更喜欢
【问题讨论】:
标签: java spring-boot jpa spring-data-jpa many-to-many