Mybatis一對多與多對一查詢處理詳解
更新時間:2021年03月04日 11:01:27 作者:KittyGuy
這篇文章主要給大家介紹了關于Mybatis一對多與多對一查詢處理的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
要點
- 主要還是結果集映射(resultMap)
- association標簽: 一個復雜類型的關聯;許多結果將包裝成這種類型(JavaBean)嵌套結果映射,關聯可以是 resultMap 元素,或是對其它結果映射的引用
- collection標簽: 一個復雜類型的集合(List)嵌套結果映射,集合可以是resultMap元素,或是對其它結果映射的引用
一對多(association)
數據庫結構

tid是student的外鍵,是teacher表的id
JavaBean
public class Student {
private int id;
private String name;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
mapper.java
public interface StudentMapper {
List<Student> getStudent();
List<Student> getStudent2();
}
Student類里面有teacher,要想查出Student中的Teacher就需要映射。
方法有二
(1)
<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="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{Anything}
</select>

(2)
<select id="getStudent2" resultMap="StudentTeacher2">
select * from mybatis.student as s ,mybatis.teacher as t where s.tid=t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="Teacher">
<result property="id" column="tid"/>
<result property="name" column="name"/>
</association>
</resultMap>

多對一
JavaBean
public class Teacher2 {
private int id;
private String name;
//一個老師對應多個學生
private List<Student2> students;
}
public class Student2 {
private int id;
private String name;
private int tid;
}
mapper.java
public interface TeacherMapper2 {
List<Teacher2> getTeacher(@Param("id") int id);
}
mapper.xml
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.DAO.TeacherMapper2">
<select id="getTeacher" parameterType="int" resultMap="teacherS">
select s.id, s.name, s.tid,t.id as tid, t.name as tname from mybatis.student as s ,mybatis.teacher as t where s.tid=t.id and t.id=#{id}
</select>
<resultMap id="teacherS" type="teacher2">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="student2">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>

小結
- 一對多和多對一區(qū)別不大
- 其實就是association(類)和collection(集合)的區(qū)別
- 還有ofType和javaType的區(qū)別
- 如果查詢結果不符合預期,請設置別名試一試
到此這篇關于Mybatis一對多與多對一查詢處理的文章就介紹到這了,更多相關Mybatis一對多與多對一查詢內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringMVC實現controller中獲取session的實例代碼
本篇文章主要介紹了SpringMVC實現controller中獲取session的實例代碼,具有一定的參考價值,有興趣的可以了解一下。2017-02-02

