项目中经常遇到需要递归查询子级结构的时候,比如省、市、区、乡镇、街道等,通过java写可能有的时候比较乱,但利用mybatis自带的查询可直接实现。
数据库表
VO类
XML写法
<resultMap id="TestMap" type="com.vo.TestVO">
<id column="id" property="id" />
<result column="name" property="name" />
<collection property="children" javaType="ArrayList" ofType="com.vo.TestVO"
select="selectChildren" column="id">
</collection>
</resultMap>
<select id="testSelect" resultMap="TestMap">
select * from test where parent_id = 0
</select>
<select id="selectChildren" resultMap="TestMap">
select * from test where parent_id = #{id}
</select>
需注意部分
“select”:为子查询的id。
“column”:为传递给子查询的字段名。
“resultMap”:为查询的返回map,因需递归查询,此处必须写返回map,不能写具体的类路径。如果子查询(图中selectChildren)写具体的类路径,则只会返回一层子结构。
结果
注:因为方法为查询自身结构,所以resultMap为同一个,当需查询另一张表时,另外单独建一个resultMap即可。