在Spring Boot中,我无法建立关系
我在尝试用Spring Boot构建一个电商API。我使用Spring Data JPA来建模和设计关系,但不知为何,我无法实现这个一对多关系。
我有一个Category实体
package xyz.rahamatj.daraz_like.models;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import java.util.List;
@Entity
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "categories_sequence_gen")
@SequenceGenerator(name = "categories_sequence_gen", sequenceName = "categories_id_seq", allocationSize = 1)
private Long id;
private String name;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Product> products;
public Category() {
}
public Category(String name) {
this.name = name;
}
public Category(Long id, String name) {
this.id = id;
this.name = name;
this.products = products;
}
public Category(String name, List<Product> products) {
this.name = name;
this.products = products;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "category")
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
并且我有一个Product实体
package xyz.rahamatj.daraz_like.models;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "products_sequence_gen")
@SequenceGenerator(name = "products_sequence_gen", sequenceName = "products_id_seq", allocationSize = 1)
private Long id;
private String name;
private double rating;
private double price;
private String description;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
public Product() {
}
public Product(String name, double rating, double price, String description) {
this.name = name;
this.rating = rating;
this.price = price;
this.description = description;
// this.category = category;
}
public Product(Long id, String name, double rating, double price, String description) {
this.id = id;
this.name = name;
this.rating = rating;
this.price = price;
this.description = description;
// this.category = category;
}
}
现在我无法实现从Category到 Product的一对多关系。
解决方案
正如你在注释中所说,你得到的输出类似于:
category: {
id: 1,
title: "test",
products: []
}
原因在于这一行:
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
你对Product使用的fetch type为 LAZY。这意味着它不会从数据源隐式获取。你必须显式地从数据源获取它们。
因此,每当你从你的数据源获取一个Category时,产品都不会被包含在结果中,正是因为这个原因。 如果你也希望在响应中包含产品,并且不想进行显式调用,请设置 fetch = FetchType.EAGER。这将包含与该分类相关的所有产品。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。