jpa设计树菜单演化(二)

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,但是在迁移的时候还是不方便,例如,我把节点,放到另外一个节点下,所有子节点都需要改变的。 实现起来很麻烦,所以还是需要改进。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值