要写一个多级菜单
@Entity
@Table(name = "table_category")
public class TableCategory extends EntityId{
@Column(name = CATEGORY_NAME)
private String categoryName;
@Column(name = PARENT_CATEGORY_ID, nullable = false)
@ColumnDefault("-1")
//-1表示自己是根节点
private Long parentCategoryId;
@Column(name = LEVEL)
private Integer level;
/**
* 自关联写法,未必标准
* 该类别所有的子类别集合
* 我理解的是,mappedBy就是以哪个字段为标准,去查找指向它的外键
*/
@OneToMany(mappedBy = "parentCategory", fetch = FetchType.LAZY)
@JsonIgnore
private Set<TableCategory> childIds;
//这里的级联等级必须是refresh,写all的时候会导致删除失败
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = PARENT_CATEGORY)
private TableCategory parentCategory;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Long getParentCategoryId() {
return parentCategoryId;
}
public void setParentCategoryId(Long parentCategoryId) {
this.parentCategoryId = parentCategoryId;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Set<TableCategory> getChildIds() {
return childIds;
}
public void setChildIds(Set<TableCategory> childIds) {
this.childIds = childIds;
}
public TableCategory getParentCategory() {
return parentCategory;
}
public void setParentCategory(TableCategory parentCategory) {
this.parentCategory = parentCategory;
}
}
还是蛮奇怪的,这种写法能完成业务,且没有bug。原理是当他需要知道有多少他的children的时候,他会从表里把外键都指向他的数据读取出来。统计。
这种写法不需要维护中间表。
如果是mybatis估计会麻烦点,没试过children,Hibernate可以自动生成表结构,因此还是很方便,。