mybatis處理自關聯

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>

  此例子僅供參考,如有其它更好的解決方案,歡迎交流告知。謝謝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章