MyBatis嵌套查尋&嵌套結果查詢--復雜查詢


兩張表:

student,teacher

 

 

 

 

多對一 

studentMapper

public interface StudentMapper {

  public List<Student> getStudent();
  public List<Student> getStudent2();

}

StudentMapper.xml

<?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.wang.dao.StudentMapper">
//嵌套查詢
    <select id="getStudent" resultMap="StudentTeacher">
        select * from mybatis.student
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>


//嵌套結果查詢
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from student s,teacher t
        where s.tid = t.id
    </select>
    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>


</mapper>
<== Columns: sid, sname, tname <==        Row: 1, 小明, 王老師 <==        Row: 2, 小紅, 王老師 <==        Row: 3, 小張, 王老師 <==        Row: 4, 小李, 王老師 <==        Row: 5, 小王, 王老師 <==      Total: 5

 

一對多

TeacherMapper

public interface TeacherMapper {

    //獲取指定老師下的所有學生信息
    Teacher getTeacher(@Param("tid") int id);
}

TeacherMapper.xml

<?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.wang.dao.TeacherMapper">
<!--按結果嵌套查詢-->
    <select id="getTeacher" resultMap="TS">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t
        where s.tid=t.id and t.id=#{tid}
    </select>
    <resultMap id="TS" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
    <!--    復雜的屬性,我們需要單獨處理
            對象: association ; 集合:collection
            javaType="" 指定屬性的類型
            集合中的泛型信息,使用ofType
    -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
</mapper>
Teacher(id=1, name=王老師, 
students=[Student(id=1, name=小明, tid=1),
Student(id=2, name=小紅, tid=1),
Student(id=3, name=小張, tid=1),
Student(id=4, name=小李, tid=1),
Student(id=5, name=小王, tid=1)])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM