mybatis association嵌套association的两级嵌套问题

今天遇到了一个双表连接查询以及自关联的问题,由于第一次遇到,所以在这记下,日后好查阅

针对一个表的关联属性本身也有自关联的情况下,可以用association嵌套association的方法来处理。

以下是代码:

    <select id="selectNewsLabels" resultMap="newslabelMap">
        select id,label_name,label_content from newlabel where id=#{xxx}
    </select>
    
    <resultMap type="NewManage" id="newmanageMap">
        <id property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <result property="time" column="time"/>
        <association property="newsLabel" javaType="NewsLabel">
            <id property="id" column="id"/>
            <result property="name" column="label_name"/>
            <association property="parent" javaType="NewsLabel" select="selectNewsLabels" column="pid">
                <id property="id" column="id"/>
                <result property="name" column="label_name"/>
            </association>
        </association>
    </resultMap>
    
    <select id="selectCurrentPage" resultMap="newmanageMap">
        select l.pid,l.id,l.label_name,m.id,m.labelid,m.title,m.content,m.time from newlabel l,newmanage m 
        <where>
             l.id=m.labelid 
            <if test="title != null and title != ''">
                and title like '%${title}%'
            </if>
            <if test="labelid != null and labelid != 0">
                and labelid=#{labelid}
            </if>
        </where>
        limit #{pageStartIndex},#{pageSize}
    </select>

这样的话,就不用去另外去写一个VO类去封装这些属性了 ,简单,方便

在页面上可以用 对象.属性.属性.属性 来获得这个属性值

我第一次写的时候,把第一个association也加上select了,导致结果不正确。

猜你喜欢

转载自www.cnblogs.com/caotao0918/p/10096412.html