树的查询
介绍
我们在做权限管理时,大多都会用到树的查询 在进行查询我们需要进行递归查询,在查询时有很多方法,我最喜欢用的是把集合转换成流去处理(主要是代码少),下面是测试代码
这是返回数据DTO
public class UserFuncDTO {
private Integer funcModuleId;
private String name;
private Integer parentId;
List<UserFuncDTO> list;
public List<UserFuncDTO> getList() {
return list;
}
public void setList(List<UserFuncDTO> list) {
this.list = list;
}
public Integer getFuncModuleId() {
return funcModuleId;
}
public void setFuncModuleId(Integer funcModuleId) {
this.funcModuleId = funcModuleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
}
测试代码
@Test
public void test() {
List<UserFuncDTO> dtos = jdbcUtil();
List<UserFuncDTO> list = dtos.stream()
.filter(dto -> {return dto.getParentId() == 0; })
. map(dto -> {
dto.setList(getCategoryList(dto,dtos));
return dto;
})
.collect(Collectors.toList());
}
private List<UserFuncDTO> getCategoryList(UserFuncDTO dto, List<UserFuncDTO> dtos) {
List<UserFuncDTO> list = dtos.stream().filter(item -> {
return item.getParentId() == dto.getFuncModuleId();
}).
map(item -> {
item.setList(getCategoryList(item, dtos));
return item;
}).collect(Collectors.toList());
return list;
}
private List<UserFuncDTO> jdbcUtil(){
List<UserFuncDTO> dtos = new ArrayList<>();
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "数据库地址";
String USER = "用户名";
String PASS = "密码";
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM 表名";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
UserFuncDTO dto=new UserFuncDTO();
dto.setFuncModuleId(rs.getInt("func_module_id"));
dto.setName(rs.getString("name"));
dto.setParentId(rs.getInt("parent_id"));
dtos.add(dto);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
return dtos;
}
|