您的位置:首页 > 编程语言 > Java开发

mybatis处理自关联

2017-04-17 14:25 232 查看

mybatis处理自关联

    何为自关联我就不多说,毕竟能找到这里的肯定不会再问什么是自关联:
    本例子亲测正确运行,主要是子类查找所属父类;

   先上实体类:
public class Right {
private Integer rightno;

private String rightname;

private Integer rightstate;

private Integer rightparent;

private String rightremark;
// 权限父类(关联)
private Right right;

//省略set get方法
}

映射文件:
<?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.hansuo.traffic.dao.RightMapper">
<resultMap id="BaseResultMap" type="com.hansuo.traffic.entity.Right">
<id column="rightNo" property="rightno" jdbcType="INTEGER" />
<result column="rightName" property="rightname" jdbcType="VARCHAR" />
<result column="rightState" property="rightstate" jdbcType="INTEGER" />
<result column="rightParent" property="rightparent" jdbcType="INTEGER" />
<result column="rightRemark" property="rightremark" jdbcType="VARCHAR" />
</resultMap>
<!-- 自关联映射结果集 -->
<resultMap type="Right" id="RightRightResultMap" extends="BaseResultMap">
<association property="right" column="rightParent" select="findParent">
</association>
</resultMap>

<sql id="Base_Column_List">
rightNo, rightName, rightState, rightParent, rightRemark
</sql>
<sql id="likewhere">
<where>
<if test="rightno!=null">
and right1.rightNo LIKE CONCAT(CONCAT('%', #{rightno}),
'%')
</if>
<if test="rightname!=null">
and right1.rightName LIKE CONCAT(CONCAT('%',
#{rightname}), '%')
</if>
and right1.rightParent is not null
</where>

</sql>
<select id="findParent" parameterType="java.lang.Integer" resultType="Right">
select * from b_right where rightNo =#{rightParent}
</select>

<!--查找所有权限 -->
<select id="allRightsearch" resultMap="RightRightResultMap"
parameterType="Right">
select * from b_right right1
left join b_right right2
on right1.rightParent = right2.rightNo
<include refid="likewhere"></include>
</select>

</mapper>


  此例子仅供参考,如有其它更好的解决方案,欢迎交流告知。谢谢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java mybatis 自关联