2-Mybatis進(jìn)階

1.Mybatis 接口代理方式實(shí)現(xiàn)Dao層

2.Mybatis 映射配置文件-動態(tài)SQL

3.Mybatis 核心配置文件-分頁插件

4.Mybatis 多表操作

1.Mybatis 接口代理方式實(shí)現(xiàn)Dao層

  • 傳統(tǒng)方式實(shí)現(xiàn)Dao層,我們即要寫接口,還要寫實(shí)現(xiàn)類,而MyBatis框架可以幫助我們省略編寫Dao層接口實(shí)現(xiàn)類的步驟,程序員只需要編寫接口,由MyBatis框架根據(jù)接口定義的來創(chuàng)建該接口的動態(tài)代理對象
  • 實(shí)現(xiàn)規(guī)則
    1.映射配置文件中的名稱空間必須和Dao層接口的全類名相同
    2.映射配置文件中的增刪改查標(biāo)簽的id屬性必須和Dao層接口的方法名相同
    3.映射配置文件中的增刪改查標(biāo)簽的 parameterType屬性必須和Dao層接口方法的參數(shù)相同
    4.映射配置文件中的增刪改查標(biāo)簽的 resultType屬性必須和Dao層接口方法的返回值相同
  • 接口代理方式-(代碼實(shí)現(xiàn))
    1.刪除mapper層接口的實(shí)現(xiàn)類
    2.修改映射配置文件,其他配置不變
<mapper namespace="com.itheima.mapper.StudentMapper">

3.修改service層接口的實(shí)現(xiàn)類,采用接口代理方式實(shí)現(xiàn)功能

package com.itheima.service.Impl;

import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.StudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;

/*
    業(yè)務(wù)層實(shí)現(xiàn)類
 */
public class StudentServiceImpl implements StudentService {

    @Override
    public List<Student> selectAll() {
        List<Student> list = null;
        SqlSession sqlSession = null;
        InputStream is = null;
        try {
            //加載核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //獲取SqlSession工廠對象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //通過工廠對象獲取SqlSession對象
            sqlSession = sqlSessionFactory.openSession(true);
            //獲取StudentMapper接口的實(shí)現(xiàn)類對象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //通過實(shí)現(xiàn)類對象調(diào)用方法,接受結(jié)果
            list = mapper.selectAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            if (sqlSession != null) {
                sqlSession.close();
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回結(jié)果
        return list;
    }

    @Override
    public Student selectById(Integer id) {
        SqlSession sqlSession = null;
        InputStream is = null;
        Student student = null;
        try {
            //加載核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //獲取SqlSession工廠對象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //通過工廠對象獲取SqlSession對象
            sqlSession = sqlSessionFactory.openSession(true);
            //獲取StudentMapper接口的實(shí)現(xiàn)類對象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //通過實(shí)現(xiàn)類對象調(diào)用方法,接受結(jié)果
            student = mapper.selectById(id);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            if (sqlSession != null) {
                sqlSession.close();
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回結(jié)果
        return student;
    }

    @Override
    public Integer insert(Student stu) {

        SqlSession sqlSession = null;
        InputStream is = null;
        Integer result = null;
        try {
            //加載核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //獲取SqlSession工廠對象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //通過工廠對象獲取SqlSession對象
            sqlSession = sqlSessionFactory.openSession(true);
            //獲取StudentMapper接口的實(shí)現(xiàn)類對象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //通過實(shí)現(xiàn)類對象調(diào)用方法,接受結(jié)果
            result = mapper.insert(stu);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            if (sqlSession != null) {
                sqlSession.close();
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回結(jié)果
        return result;
    }

    @Override
    public Integer update(Student stu) {
        SqlSession sqlSession = null;
        InputStream is = null;
        Integer result = null;
        try {
            //加載核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //獲取SqlSession工廠對象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //通過工廠對象獲取SqlSession對象
            sqlSession = sqlSessionFactory.openSession(true);
            //獲取StudentMapper接口的實(shí)現(xiàn)類對象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //通過實(shí)現(xiàn)類對象調(diào)用方法,接受結(jié)果
            result = mapper.update(stu);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            if (sqlSession != null) {
                sqlSession.close();
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回結(jié)果
        return result;
    }

    @Override
    public Integer delete(Integer id) {
        SqlSession sqlSession = null;
        InputStream is = null;
        Integer result = null;
        try {
            //加載核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //獲取SqlSession工廠對象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //通過工廠對象獲取SqlSession對象
            sqlSession = sqlSessionFactory.openSession(true);
            //獲取StudentMapper接口的實(shí)現(xiàn)類對象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //通過實(shí)現(xiàn)類對象調(diào)用方法,接受結(jié)果
            result = mapper.delete(id);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            if (sqlSession != null) {
                sqlSession.close();
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回結(jié)果
        return result;
    }
}
  • 分析動態(tài)代理對象如何生成的?
    通過動態(tài)代理開發(fā)模式,我們只編寫一個接口,不寫實(shí)現(xiàn)類,我們通過getMapper()方法最終獲取到org.apache.ibatis.binding.MapperProxy代理對象,然后執(zhí)行功能,而這個代理對象正是MyBatis使用了JDK的動態(tài)代理技術(shù),幫助我們生成了代理實(shí)現(xiàn)類對象,從而可以進(jìn)行相關(guān)持久化操作
  • 分析方法是如果執(zhí)行的?
    動態(tài)代理實(shí)現(xiàn)類對象執(zhí)行方法的時候最終調(diào)用mapperMethod.execute()方法,這個方法中通過switch語句根據(jù)操作類型來判斷是新增,修改,刪除,查詢操作,最后一步回到了MyBatis最原生的SqlSession方式執(zhí)行增刪改查

2.Mybatis 映射配置文件-動態(tài)SQL

  • 動態(tài)SQL指的就是SQL語句可以根據(jù)條件或者參數(shù)的不同進(jìn)行動態(tài)的變化
  • 動態(tài)SQL標(biāo)簽
    1.<if>: 條件判斷標(biāo)簽
    2.<where>: 條件標(biāo)簽,如果有動態(tài)條件,則使用該標(biāo)簽代替where關(guān)鍵字
<if test= "判斷條件">
  查詢條件
</if>
<select id="selectCondition" resultType="student" parameterType="student">
<!--Select * from student WHERE id=#{id} and name =#{name} and age =#{age}-->
<!-- <where>標(biāo)簽就是替換sql語句中的where關(guān)鍵字的-->
        Select * from student
        <where>
            <if test="id != null">
                id =#{id}
            </if>
            <if test="name != null">
                and name =#{name}
            </if>
            <if test="age != null">
                and age =#{age}
            </if>
        </where>
    </select>

3.<foreach>: 循環(huán)遍歷標(biāo)簽,適用于多個參數(shù)或者的關(guān)系

<foreach collection="" open="" item="" separator="">
            獲取參數(shù)
</foreach>

屬性
conllection: 參數(shù)容器類型,(list-集合,array-數(shù)組)
open: 開始的SQL語句
close: 結(jié)束的SQL語句
item: 參數(shù)變量名
separator: 分隔符

<!-- 查詢多個id-->
<select id="forEach" resultType="student" parameterType="list">
<!--         Select * from student where id in (1,2,3)-->
        Select * from student
        <where>
            <foreach collection="list" open="id in ( " close=")"  item="id" separator=",">
                #{id}
            </foreach>
        </where>
</select>

SQL 片段抽取>

  • 將重復(fù)性的SQL語句進(jìn)行抽取,以達(dá)到復(fù)用的效果
  • <sql>: 抽取SQL語句標(biāo)簽
<sql id="片段唯一標(biāo)識"> 抽取的SQL語句 </sql>
  • <include>: 引入SQL片段標(biāo)簽
<sql refid="片段唯一標(biāo)識"/> 
  • 映射配置文件中的抽取與引用
    <sql id="select">Select * from student</sql>
    <!--    查詢功能-->
    <select id="selectAll" resultType="student">
        <include refid="select"/>
    </select> 

3.Mybatis 核心配置文件-分頁插件

  • PageHelper: 第三方分頁助手,將復(fù)雜的分頁操作進(jìn)行封裝,從而讓分頁功能變得非常簡單
  • <plugins>: 集成插件標(biāo)簽
  • 分頁相關(guān)API
    PageHelper: 分頁助手功能類
    startPage(): 設(shè)置分頁參數(shù) 參數(shù)1:當(dāng)前頁 參數(shù)2:當(dāng)前頁顯示的條數(shù)
  • 分頁插件實(shí)現(xiàn)步驟
    1.導(dǎo)入jar包
pagehelper-5.1.10.jar
jsqlparser-3.1.jar

2.在核心配置文件中集成分頁助手插件

    <!--集成分頁助手插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

3.在測試類中使用分頁助手相關(guān)API實(shí)現(xiàn)分類功能

//通過分頁助手實(shí)現(xiàn)分頁功能
        //第一頁: 顯示三條
        //PageHelper.startPage(1,3);
        //第二頁:顯示三條,以此類推
        PageHelper.startPage(2,3);
        List<Student> list = mapper.selectAll();
        for (Student student : list) {
            System.out.println(student);
        }
        //分頁相關(guān)的參數(shù)
        PageInfo<Student> info = new PageInfo<>(list);
        System.out.println("總條數(shù):"+info.getTotal());
        System.out.println("總頁數(shù):"+info.getPages());
        System.out.println("當(dāng)前頁:"+info.getPageNum());
        System.out.println("每頁顯示的條數(shù):"+info.getPageSize());
        System.out.println("上一頁:"+info.getPrePage());
        System.out.println("下一頁:"+info.getNextPage());
        System.out.println("是否是第一頁:"+info.isIsFirstPage());
        System.out.println("是否是最后頁:"+info.isIsLastPage());

分頁插件相關(guān)參數(shù)

  • PageInfo: 封裝分頁相關(guān)參數(shù)的功能類

    核心方法:
    核心方法

4.Mybatis 多表操作

多表模型分類
一對一: 在任意一方建立外鍵,關(guān)聯(lián)對方主鍵
一對多: 在多的一方建立外鍵,關(guān)聯(lián)一的一方主鍵
多對多: 借助中間表,中間表至少兩個字段,分別關(guān)聯(lián)兩張表的主鍵

一對一

  • <resultMap>: 配置字段和對象屬性的映射關(guān)系標(biāo)簽
    id屬性: 唯一標(biāo)識
    type屬性: 實(shí)體類對象類型
  • <id>: 配置主鍵映射關(guān)系標(biāo)簽
  • <result>: 配置非主鍵映射關(guān)系標(biāo)簽
    column屬性: 表中字段名稱
    property屬性: 實(shí)體對象變量名稱
  • <association>: 配置被包含對象的映射關(guān)系標(biāo)簽
    property屬性: 被包含對象的變量名
    javaType屬性: 被包含對象的數(shù)據(jù)類型
  • 封裝類
//  空參有構(gòu)造方法,get和set和toString()方法省略,
public class Card {
    private Integer id;
    private String number;
    private  Person P;
}
// 空參有參構(gòu)造方法,get和set和toString()方法省略
public class Person {
    private Integer id;
    private String name;
    private Integer age;
  }
  • 數(shù)據(jù)準(zhǔn)備
CREATE DATABASE db12;
USE db12;
CREATE TABLE person(
        id INT PRIMARY KEY AUTO_INCREMENT,
        NAME VARCHAR(20),
        age INT
);
INSERT INTO person VALUES(NULL,'張三',23);
INSERT INTO person VALUES(NULL,'李四',24);
INSERT INTO person VALUES(NULL,'王五',25);
CREATE TABLE card (
        id INT PRIMARY KEY AUTO_INCREMENT,
        number VARCHAR(30),
        pid INT,
        CONSTRAINT cp_fk FOREIGN KEY (pid) REFERENCES person(id)
);
INSERT INTO card VALUES(NULL,'123123',1);
INSERT INTO card VALUES(NULL,'456456',2);
INSERT INTO card VALUES(NULL,'789789',3);
  • 核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--映射配置文件-->
<configuration>

    <!--引入數(shù)據(jù)庫連接的配置文件-->
    <properties resource="JDBC.properties"/>

    <!--繼承LOG4J日志信息-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <!--起別名-->
    <typeAliases>
        <!--<typeAlias type="com.itheima.bean" alias="***"/>-->
    <!--給bean這個包下所有的包起一個別名,作為了解-->
    <package name="com.itheima.bean"/>
    </typeAliases>

    <!--集成分頁助手插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

    <!--environments配置數(shù)據(jù)庫環(huán)境,環(huán)境可以有多個,default屬性指定使用的是哪個-->
    <environments default="mysql">
        <!--environment配置數(shù)據(jù)庫環(huán)境 id屬性代表唯一的標(biāo)識-->
        <environment id="mysql">
            <!-- transactionManager事務(wù)的管理 type屬性,采用JDBC默認(rèn)的事務(wù)-->
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource數(shù)據(jù)源信息 type屬性 連接池-->
            <dataSource type="POOLED">
                <!--property獲取數(shù)據(jù)庫連接的數(shù)據(jù)信息-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--mappers引入映射文件-->
    <mappers>
        <!--mapper 引入指定的映射配置文件 resource屬性: 指定映射配置文件的名稱-->
        <mapper resource="com/itheima/one_to_one/OneToOneMapper.xml"></mapper>
    </mappers>
</configuration>
  • 映射配置文件
<?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">
<!--動態(tài)代理配置接口類-->
<mapper namespace="com.itheima.table01.OneToOneMapper">
    <!--配置字段和實(shí)體對象屬性的映射關(guān)系-->
    <resultMap id="OneToOne" type="card">
        <!--id標(biāo)簽是專門對主鍵進(jìn)行配置的-->
        <id column="cid" property="id"/>
        <!--其他屬性用result標(biāo)簽-->
        <result column="number" property="number"/>
        <!--
            association: 配置被包含對象的映射關(guān)系
            property: 被包含對象的變量名
            javaType: 被包含對象的實(shí)際的數(shù)據(jù)類型
        -->
        <association property="P" javaType="person">
            <id column="pid" property="id"/>
            <result column="name" property="name"/>
            <result column="age" property="age"/>
        </association>
    </resultMap>

    <select id="selectAll" resultMap="OneToOne">
        SELECT c.id cid,number,pid,NAME,age FROM card c,person p WHERE c.pid=p.id
    </select>
</mapper>
  • 測試單元
public class Test01 {
    @Test
    public void selectAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        OneToOneMapper mapper = sqlSession.getMapper(OneToOneMapper.class);
        List<Card> cards = mapper.selectAll();
        for (Card cs : cards) {
            System.out.println(cs);
        }
        sqlSession.close();
        is.close();
    }
}
  • 打印結(jié)果


    image.png

一對多

  • <collection>: 配置被包含集合對象的映射關(guān)系標(biāo)簽
    property屬性: 被包含集合對象的變量名
    ofType屬性: 集合中保存的對象數(shù)據(jù)類型
  • 封裝類
//  空參有構(gòu)造方法,get和set和toString()方法省略,
public class Classes {
    private Integer id; //主鍵id
    private  String name;   //班級名稱
    private List<Student> students; //班級中所有學(xué)生對象
}
//  空參有構(gòu)造方法,get和set和toString()方法省略,
public class Student {
    private Integer id; //主鍵id
    private String name;    //學(xué)生新明
    private Integer age;    //學(xué)生年齡
}
  • 數(shù)據(jù)準(zhǔn)備
CREATE TABLE classes(
        id INT PRIMARY KEY AUTO_INCREMENT,
        NAME VARCHAR(20)
);
INSERT INTO classes VALUES(NULL,'一班');
INSERT INTO classes VALUES(NULL,'二班');
CREATE TABLE student(
        id INT  PRIMARY KEY AUTO_INCREMENT,
        NAME VARCHAR(30),
        age INT,
        cid INT,
        CONSTRAINT cs_fk FOREIGN KEY (cid) REFERENCES classes(id)
);
INSERT INTO student VALUES(NULL,'張三',23,1);
INSERT INTO student VALUES(NULL,'李四',24,1);
INSERT INTO student VALUES(NULL,'王五',25,2);
INSERT INTO student VALUES(NULL,'趙六',26,2);
  • 核心配置文件,只需添加映射文件路徑
    <mappers>
        <!--mapper 引入指定的映射配置文件 resource屬性: 指定映射配置文件的名稱-->
        <mapper resource="com/itheima/one_to_one/OneToOneMapper.xml"></mapper>
        <mapper resource="com/itheima/one_to_many/OneToManyMapper.xml"></mapper>
    </mappers>
  • 映射配置文件
<?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.itheima.table02.OneToManyMapper">
    <resultMap id="OnToMany" type="classes">
        <id column="cid" property="id"/>
        <result column="cname" property="name"/>
        <!--
        collection: 配置被包含的集合對象映射關(guān)系
        property: 被包含對象的變量名
        ofType: 被包含對象的實(shí)際數(shù)據(jù)類型
        -->
        <!--這里的ofType:  指的是list集合中保存的實(shí)際數(shù)據(jù)類型-->
        <collection property="students" ofType="Student">
            <id column="sid" property="id"/>
            <result column="sname" property="name"/>
            <result column="sage" property="age"/>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="OnToMany">
        SELECT c.id cid,c.name cname, s.id sid,s.name sname,s.age sage FROM classes c,student s WHERE c.id=s.cid;
    </select>
</mapper>
  • 接口類代碼
package com.itheima.table02;

import com.itheima.bean.Classes;
import java.util.List;

public interface OneToManyMapper {
    //查詢?nèi)康墓δ?    public abstract List<Classes> selectAll();
}
  • 測試單元代碼
public class Test01 {
    @Test
    public void selectAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        OneToManyMapper mapper = sqlSession.getMapper(OneToManyMapper.class);
        List<Classes> classes = mapper.selectAll();
        for (Classes cs : classes) {
            System.out.println(cs.getId()+","+cs.getName());
            List<Student> students = cs.getStudents();
            for (Student student : students) {
                System.out.println(student);
            }
        }
        sqlSession.close();
        is.close();
    }
}
  • 測試結(jié)果
    測試結(jié)果

多對多

  • 封裝類
public class Student {
    private Integer id; //主鍵id
    private String name;    //學(xué)生新明
    private Integer age;    //學(xué)生年齡
    private List<Course> courses;   //指當(dāng)前學(xué)生所選擇的課程集合
}
public class Course {
    private Integer id; //主鍵id
    private String name;   //課程名稱
}
  • 數(shù)據(jù)準(zhǔn)備
CREATE TABLE course(
        id INT PRIMARY KEY AUTO_INCREMENT,
        NAME VARCHAR(20)
);
INSERT INTO course VALUES(NULL,'語文');
INSERT INTO course VALUES(NULL,'數(shù)學(xué)');

CREATE TABLE stu_cr(
        id INT  PRIMARY KEY AUTO_INCREMENT,
        sid INT,
        cid INT,
        CONSTRAINT sc_fk1 FOREIGN KEY (sid) REFERENCES student(id),
        CONSTRAINT sc_fk2 FOREIGN KEY (cid) REFERENCES course(id)
);
INSERT INTO stu_cr VALUES(NULL,1,1);
INSERT INTO stu_cr VALUES(NULL,1,2);
INSERT INTO stu_cr VALUES(NULL,2,1);
INSERT INTO stu_cr VALUES(NULL,2,2);
  • 接口
public interface ManyToManyMapper {
    //查詢?nèi)康墓δ?    public abstract List<Student> selectAll();
}
  • 映射配置文件
<?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.itheima.table03.ManyToManyMapper">
    <resultMap id="manyToMany" type="student">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <result column="sage" property="age"/>
        <collection property="courses" ofType="course">
            <id column="cid" property="id"/>
            <result column="cname" property="name"/>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="manyToMany">
        SELECT sc.sid ,s.name sname ,s.age sage,sc.cid ,c.name cname FROM student s,course c, stu_cr sc WHERE sc.sid=s.id AND sc.cid=c.id;
    </select>
</mapper>
  • 核心配置文件只需添加,映射配置文件路徑
    <!--mappers引入映射文件-->
    <mappers>
        <!--mapper 引入指定的映射配置文件 resource屬性: 指定映射配置文件的名稱-->
        <mapper resource="com/itheima/one_to_one/OneToOneMapper.xml"></mapper>
        <mapper resource="com/itheima/one_to_many/OneToManyMapper.xml"></mapper>
        <mapper resource="com/itheima/many_to_many/ManyToManyMapper.xml"></mapper>
    </mappers>
  • 測試單元
  @Test
    public void selectAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ManyToManyMapper mapper = sqlSession.getMapper(ManyToManyMapper.class);
        List<Student> studentList = mapper.selectAll();
        for (Student student : studentList) {
            System.out.println(student.getId()+","+student.getName()+","+student.getAge());
            List<Course> courses = student.getCourses();
            for (Course cours : courses) {
                System.out.println("/t"+cours);
            }
        }
        sqlSession.close();
        is.close();
    }
}
  • 測試結(jié)果
    測試結(jié)果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末脊另,一起剝皮案震驚了整個濱河市踩麦,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件忙芒,死亡現(xiàn)場離奇詭異潮峦,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)窄做,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吻商,“玉大人艾帐,你說我怎么就攤上這事±趾幔” “怎么了蛔外?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵夹厌,是天一觀的道長豹爹。 經(jīng)常有香客問我,道長或南,這世上最難降的妖魔是什么孩等? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮采够,結(jié)果婚禮上肄方,老公的妹妹穿的比我還像新娘。我一直安慰自己蹬癌,他們只是感情好权她,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布虹茶。 她就那樣靜靜地躺著,像睡著了一般隅要。 火紅的嫁衣襯著肌膚如雪蝴罪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天步清,我揣著相機(jī)與錄音要门,去河邊找鬼。 笑死廓啊,一個胖子當(dāng)著我的面吹牛暂衡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播崖瞭,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼狂巢,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了书聚?” 一聲冷哼從身側(cè)響起唧领,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎雌续,沒想到半個月后斩个,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡驯杜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年受啥,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鸽心。...
    茶點(diǎn)故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡滚局,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出顽频,到底是詐尸還是另有隱情藤肢,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布糯景,位于F島的核電站嘁圈,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蟀淮。R本人自食惡果不足惜最住,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望怠惶。 院中可真熱鬧涨缚,春花似錦、人聲如沸甚疟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽览妖。三九已至轧拄,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間讽膏,已是汗流浹背檩电。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留府树,地道東北人俐末。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像奄侠,于是被迫代替她去往敵國和親卓箫。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容