害!这两天终于做了点和之前不一样的增删改查——树型结构,虽说是也没啥技术含量吧😂
首先,建立一个树型数据表,字段包括(id、sort_name、parent_id等)如图:
其次是实体类bean,如下
@Getter
@Setter
public class Sort {
private Long id;
private Long parentId;
private String sortName;
private Timestamp createTime;
private Timestamp updateTime;
@Transient
private List<Sort> children;
然后编写SQL语句,如下:
① mapper
List<Sort> getAllSort();
② xml文件
<resultMap id="BaseResultTreeMap" type="org.sang.bean.Sort">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="parent_id" jdbcType="BIGINT" property="parentId"/>
<result column="parent_Name" jdbcType="VARCHAR" property="parentName"/>
<result column="sort_name" jdbcType="VARCHAR" property="sortName"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
<!--使用mybatis collection 进行集合查询-->
<collection property="children" ofType="Sort" select="selectTree" column="id" javaType="java.util.ArrayList"/>
</resultMap>
<!--父级查询-->
<select id="getAllSort" resultMap="BaseResultTreeMap">
select * from sort s where s.id in ('11','12','13','14')
</select>
<!--关联集合查询-->
<select id="selectTree" parameterType="String" resultMap="BaseResultTreeMap">
select * from sort s where s.parent_id=#{id}
</select>
简单编写service部分,调用父级查询
public List<Sort> selectTree() {
return sortMapper.getAllSort();
}
最后,简单controller实现🤔
@RequestMapping(value = "/all", method = RequestMethod.GET)
public List<Sort> getAllSorts() {
return sortService.selectTree();
}
🆗完工!