mybatie 一对一一对多实现

association是用于一对一和多对一,而collection是用于一对多的关系

<!--按照结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
    select t.name tname,t.id tid,s.name sname ,s.id sid
    from teacher t left join student s on t.id=s.tid
    where t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="com.wyl.pojo.Teacher">
    <result property="name" column="tname"/>
    <result property="id" column="tid"/>
    <collection property="student" ofType="com.wyl.pojo.Student" javaType="ArrayList">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>

</resultMap>
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id=#{tid}
    </select>
    <resultMap id="TeacherStudent2" type="com.wyl.pojo.Teacher">
        <collection property="student" javaType="ArrayList" ofType="com.wyl.pojo.Student" select="getStudent" column="id">
        </collection>
    </resultMap>
    <select id="getStudent" resultType="com.wyl.pojo.Student">
        select * from student   where tid=#{tid}
    </select>

================================================

<!-- 方式1 按照查询嵌套处理-->
    <resultMap id="StudentTeacher" type="com.wyl.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性需要单独处理-->
        <!--对象 association 集合clooection-->
        <!--property 写student 中的 teacher  column对应数据库字段-->
        <association property="teacher" column="tid" javaType="com.wyl.pojo.Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>

    <select id="getTeacher" resultType="com.wyl.pojo.Teacher">
        select * from Teacher
    </select>
<!--方式2 按照结果嵌套处理-->
    <resultMap id="StudentTeacher2" type="com.wyl.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.wyl.pojo.Teacher">
            <result property="name" column="tname"/>
            <result property="id" column="tid"/>
        </association>
    </resultMap>
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id as sid,s.name as sname,t.name as tname,t.id as tid
        from student s left join teacher t
        on s.tid=t.id
    </select>
上一篇:xml文件中的resultMap


下一篇:达梦数据库 表被锁的处理办法