一年前写过一篇关于省市区三级联动的,当时的那篇 省 市 区 分为了三张表,但现实工作中,往往是单张表 ,然后自己查自己.
现在我以这样的情况重写写一篇.
先看看表结构
这里我们关注主键Id,名称以及父级Id
在这里我们能看到,我们表中 将 省 市 区/县 都写在了一张表内,通过父级Id建立连接.
实体类根据Mybatis逆向工程来生成,除了表中属性外 添加一个额外的属性 List childrenList;
public class ShoppingArea {
//主键Id
private Long id;
private Date addtime;
private Boolean deletestatus;
private String areaname;
private Integer level;
private Integer sequence;
//父级Id
private Long parentId;
private Boolean common;
//子级列表 非表属性
private List<ShoppingArea> childrenList;
//getter
//setter
}
在逆向工程生成的Dao层接口mapper.java如下:
public interface ShoppingAreaMapper {
int deleteByPrimaryKey(Long id);
int insert(ShoppingArea record);
int insertSelective(ShoppingArea record);
ShoppingArea selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(ShoppingArea record);
int updateByPrimaryKey(ShoppingArea record);
//根据父级id找子级
List<ShoppingArea> selectByParentId(Long parentId);
//查询所有
List<ShoppingArea> selectAll();
}
mapper.xml如下:
<mapper namespace="com.test.dao.ShoppingAreaMapper" >
<resultMap id="BaseResultMap" type="com.test.entity.ShoppingArea" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="addTime" property="addtime" jdbcType="TIMESTAMP" />
<result column="deleteStatus" property="deletestatus&