从数据库查询的每一条数据都包含id和fid字段,将获得的数据转换成树形结构
假设从数据库查询出来的数据对应的实体类:
public class department {
private int id;
private int fid;
private String name;
private List<department> list;
public department() {
}
public department(int id, int fid, String name, List<department> list) {
this.id = id;
this.fid = fid;
this.name = name;
this.list = list;
}
.......
}
将获得数据转化成属性结构
public class DepartmentUtil {
public List<department> transDepartment(List<department> rootList){
List<department> nodeList = new ArrayList<>();
for (department department : rootList) {
if (department.getId()==0){//表明是一级父类
nodeList.add(department);
}
department.setList(setChild(department.getId(),rootList));
}
return nodeList;
}
public List<department> setChild(int id, List<department> list ){
List<department> childList = new ArrayList<>();
for (department department : list) {
if (id == department.getFid()){
childList.add(department);
}
}
for (department department : childList) {
department.setList(setChild(department.getId(),list));
}
if (childList.size()==0){
return null;
}
return childList;
}
}
通过sql一对多方式实现树形结构的数据格式
<resultMap id="cityMap" type="com.jiucheng.vo.city">
<id column="CityID" property="CityID"/>
<result column="CityName" property="CityName"/>
<result column="RootID" property="RootID"/>
<result column="Child" property="Child"/>
<result column="Layer" property="Layer"/>
<result column="Sort" property="Sort"/>
<result column="Isopen" property="Isopen"/>
<collection property="list" ofType="com.jiucheng.vo.city"
column="CityID" select="getChildCity"/>
</resultMap>
<select id="findAll" resultMap="cityMap">
select * from city where RootID = 0
</select>
<select id="getChildCity" resultType="com.jiucheng.vo.city">
select * from city WHERE RootID = #{CityID}
</select>
实体类为数据库的映射对应的实体类