多对一的处理

 

第一种是根据Student表里的tid去teacher再去查一次,将查询结果映射为resulttype Student类的第三个属性Teacher,以为是引用类型,所以要指明javatype

 

 

 第二种是将需要的字段查询出来之后只对结果进行处理,将查询的列名映射到Student的三个属性,但是第三个属性为teacher,所以使用asosiatid联系到Teacher类,然后将查询到的teacher表里的tname映射到teacher类里的name属性

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.guo.dao.StudentMapper">
    <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="com.guo.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.guo.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    <resultMap id="StudentTeacher" type="com.guo.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="com.guo.pojo.Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="com.guo.pojo.Teacher">
        select * from teacher where id=#{id}
    </select>
</mapper>

 

posted on 2023-02-03 02:44  大风吹过12138  阅读(18)  评论(0)    收藏  举报

导航