使用Springboot和mybatis框架开发,程序可能用到的表为菜单权限表t_sys_menu,实现菜单权限表的树状结构接口,给出Controller层,Service层,Service实现类,Dao层,,mapper.xml文件
时间: 2024-03-28 07:42:01 浏览: 63
好的,下面是给出的代码示例:
Controller层:
```java
@RestController
@RequestMapping("/menu")
public class MenuController {
@Autowired
private MenuService menuService;
@GetMapping("/getTreeMenu")
public List<Menu> getTreeMenu() {
return menuService.getMenuTree();
}
}
```
Service层:
```java
public interface MenuService {
List<Menu> getMenuTree();
}
```
Service实现类:
```java
@Service
public class MenuServiceImpl implements MenuService {
@Autowired
private MenuMapper menuMapper;
@Override
public List<Menu> getMenuTree() {
List<Menu> menuList = menuMapper.getMenuList();
List<Menu> rootMenus = new ArrayList<>();
Map<Long, Menu> menuMap = new HashMap<>();
for (Menu menu : menuList) {
menuMap.put(menu.getId(), menu);
if (menu.getParentId() == 0) {
rootMenus.add(menu);
}
}
for (Menu menu : menuList) {
if (menu.getParentId() != 0) {
Menu parentMenu = menuMap.get(menu.getParentId());
if (parentMenu != null) {
parentMenu.addChild(menu);
}
}
}
return rootMenus;
}
}
```
Dao层:
```java
@Mapper
public interface MenuMapper {
List<Menu> getMenuList();
}
```
Mapper.xml文件:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.MenuMapper">
<resultMap type="com.example.entity.Menu" id="BaseResultMap">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="url" property="url" jdbcType="VARCHAR"/>
<result column="parent_id" property="parentId" jdbcType="BIGINT"/>
</resultMap>
<select id="getMenuList" resultMap="BaseResultMap">
SELECT * FROM t_sys_menu
</select>
</mapper>
```
注意:这里的Menu实体类需要自己定义并实现addChild方法,用于将子菜单添加到父菜单中。
另外,这里只是提供一个简单的示例,实际情况中需要根据具体需求进行调整。
阅读全文