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>
此例子僅供參考,如有其它更好的解決方案,歡迎交流告知。謝謝