1. 程式人生 > 實用技巧 >Mybatis處理複雜Sql(association/collection)

Mybatis處理複雜Sql(association/collection)

Mybatis處理複雜Sql(association/collection)

1、按照查詢巢狀處理

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <!--複雜屬性單獨處理
                物件:association
                集合:collection
            -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    <collection property=""/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{tid};
</select>

2、按照結果巢狀處理

<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname
    from student s,teacher t
    where s.id = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
    <result column="sid" property="id"/>
    <result column="sname" property="name"/>
    <!--複雜屬性單獨處理
            物件:association
            集合:collection
        -->
    <association property="teacher" javaType="Teacher">
        <result column="tname" property="name"/>
    </association>
    <collection property=""/>
</resultMap>