一、树状结构
MySQL数据库本身并不直接支持树状结构的存储,但它提供了足够的灵活性,允许我们通过不同的方法来模拟和实现树状数据结构。具体方法看下文。
数据库表结构:
实现效果
查询的结果像树一样
二、使用
以Catalog数据表,findAll()方法举例
2.1 controller
@RestController
@RequestMapping("catalog")
public class CatalogController {@Autowiredprivate CatalogService catalogService;@GetMapping("findAll")public Result findAll(){return Result.success(catalogService.findAll());}
}
2.2service
public interface CatalogService {List<Catalog> findAll();
}
@Service
public class CatalogServiceImpl implements CatalogService {@Autowiredprivate CatalogMapper catalogMapper;@Overridepublic List<Catalog> findAll() {
// 在这里直接调用findByParentId()方法,等于说mapper的findAll()没用了return catalogMapper.findByParentId(0);}}
2.3mapper--有findAll()方法继承了BaseMapper
public interface CatalogMapper extends BaseMapper<Catalog> {List<Catalog> findByParentId(Integer parentId);
}
<collection property="studentCatalog" select="findByParentId" column="id">
利用递归函数,父节点id作为参数,直到没有父节点id结束
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itqq.mapper.CatalogMapper"><resultMap id="catalog" type="Catalog"><id property="id" column="id"></id><result property="name" column="name"></result><result property="parentId" column="parent_id"></result><collection property="studentCatalog" select="findByParentId" column="id"></collection></resultMap>
<!--不用也行,可以在CatalogServiceImpl,直接调用findByParentId传id=0就行--><select id="findAll" resultMap="catalog">SELECT * FROM catalog where parent_id = 0</select><select id="findByParentId" resultMap="catalog">select * from catalog where parent_id = #{parentId}</select>
</mapper>
2.4pojo
@Data
public class Catalog implements Serializable {private static final long serialVersionUID = 152326L;private int id;private String name;private String parentId;private List<Catalog> studentCatalog;
}
总结结束,使用时可以按需修改!!!