<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jt.mapper.RightsMapper">
<!--利用左查询,查询出同表父子关系表-->
<select id="getRights" resultMap="rightsRM">
SELECT p.id,p.name,p.parent_id,p.path,p.level,p.created,p.updated,
c.id AS c_id,c.name AS c_name,c.parent_id AS c_parent_id,c.path AS c_path,
c.level AS c_level,c.created AS c_created,c.updated AS c_updated
FROM
(SELECT * FROM rights WHERE parent_id=0) AS p
LEFT JOIN
rights AS c
ON p.id =c.parent_id
</select>
<!--
1.id 标签代表逐渐(每张表都会有一个主键)
column: 返回集的字段名
property: 封装的对象对应的属性
2.result 标签代表主键以外的字段
column: 返回集的字段名
property: 封装的对象对应的属性
-->
<resultMap id="rightsRM" type="Rights" autoMapping="true">
<id column="id" property="id"/>
<!--oftype pojo里面对应对象的集合中的类型-->
<collection property="children" ofType="Rights">
<!--下面的数据库字段名字和对象里的属性不符合,需要一个一个写出来-->
<id column="c_id" property="id"/>
<result column="c_name" property="name" />
<result column="c_parent" property="parentId" />
<result column="c_path" property="path" />
<result column="c_level" property="level" />
<result column="c_created" property="created" />
<result column="c_updated" property="updated" />
</collection>
</resultMap>
<!--利用分表关联查询-->
<select id="getRights2" resultMap="RightsRM">
select *from rights where parent_id = 0
</select>
<resultMap id="RightsRM" type="Rights" autoMapping="true">
<id property="id" column="id"></id>
<collection property="children" ofType="Rights" select="childrenIdByParent" column="id"/>
</resultMap>
<select id="childrenIdByParent" resultType="Rights" >
select * from rights where parent_id = #{id}
</select>
</mapper>
SQL语句两种方式实现关联查询
最新推荐文章于 2024-08-04 20:30:19 发布