我有这样的mysql表
https://i.stack.imgur.com/ON3JL.png
这是此表的实体类
Where(clause = "active =1")
@Entity
@Table(name = "category", catalog = "businessin")
public class Category implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
private String name;
private Integer parentId;
private Integer active;
private String pic;
@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
private List<Product> products = new ArrayList<Product>();
setters&getter
}
我正在使用Spring Rest和Spring Data(jpaRepository(构建RESTful API。
我希望在将控制器的主要类别打印为 JSON 响应时,我希望它们还有一个子类别列表这个的例子
[
{
id: 1,
name: "Electronics",
parentId: 0,
active: 1,
pic: null
}]
对此
[
{
id: 1,
name: "Electronics",
parentId: 0,
active: 1,
pic: null
subCategories: [Mobile, Laptops]
}]
让你
的实体像这样很简单
@Where(clause = "active =1")
@Entity
@Table(name = "category" )
public class Category implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
private String name;
@Column(nullable=false,columnDefinition="int default 1")
private Integer active;
private String pic;
@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
private List<Product> products = new ArrayList<Product>();
@ManyToOne
@JoinColumn(name="parent_id")
@JsonIgnore
// @ColumnDefault("0")
private Category parentId;
@OneToMany(mappedBy="parentId")
private List<Category> subCategories=new ArrayList<>();
setters and getters
}