java代码:
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer level;
private String url;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Category parent; // 父级菜单
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + ", level=" + level + ", url=" + url
+ ", parent=" + parent + "]";
}
}
生成表如图:
初始化sql:
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('1', '0', '根目录', NULL, NULL);
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('2', '1', '河北', NULL, '1');
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('3', '1', '山东', NULL, '1');
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('4', '2', '石家庄', NULL, '2');
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('5', '2', '邢台', NULL, '2');
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('6', '2', '济南', NULL, '3');
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('7', '3', '桥东区', NULL, '4');
INSERT INTO `category` (`id`, `level`, `name`, `url`, `parent_id`) VALUES ('8', '3', '桥西区', NULL, '4');
java代码:
Page<Category> page = categoryRepository.findAll(PageRequest.of(0, 20)); // 第一个参数如果是1的话,查到的是第二页的数据
Optional<Category> findById = categoryRepository.findById(6);
Category category2 = findById.get();
System.out.println(category2);
结果:
Category [id=6, name=济南, level=2, url=null,
parent=Category [id=3, name=山东, level=1, url=null,
parent=Category [id=1, name=根目录, level=0, url=null,
parent=null]]
]
这样设计,可以方便的知道parent,但是在迁移的时候还是不方便,例如,我把节点,放到另外一个节点下,所有子节点都需要改变的。 实现起来很麻烦,所以还是需要改进。