mybatis的理解(中)(Mapper代理开发)

http://t.csdnimg.cn/58uNx    log4j(日志的配置)

http://t.csdnimg.cn/rQF77    mybatis的理解(上)(包括xml配置信息进行CRUD)

http://t.csdnimg.cn/GuJGu   mybatis的理解(下)(注解开发)

首先我们看一下项目结构

        在上述的项目结构当中我们在resources下,有意的把teachersMapper.xml和teachersMapper 接口路经设为一样,方便于配置teachersMapper.xml当中的namespace空间。

        这里我们就以teachers这个JavaBean为例,

下面我们看一下teachersMapper.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文件 空间名值唯一  空间名值+id-->
<mapper namespace="com.Mapper.teachersMapper">


    <select id="selectAll" resultType="com.pojo.teachers">
        select *
        from teachers;
    </select>
    <!--
        * 参数占位符
        1.#{}: 会将其替换成?,为了防止SQL注入
        2.${}: 拼SQL,会存在SQL注入
        3.使用时机
            *参数传递的时候:#{}
            *表明或列明不固定的情况下:${} 会存在SQL注入
       *参数类型
            parameterType:用于设置参数类型 可以省略不写
       *特殊字符处理
            1.转义字符
            2.CDATA区
    -->
    <select id="selectOne" parameterType="string" resultType="com.pojo.teachers">
        select *
        from teachers
        where tno = #{tno};
    </select>


    <!--
    条件查询
    -->
    <select id="selectByCondition" resultType="com.pojo.teachers">
        select *
        from teachers
        where start = #{start}
          and tno like #{tno}
          and depart like #{depart};
    </select>
    <select id="selectByConditionObj" resultType="com.pojo.teachers">
        select *
        from teachers
        where start = #{start}
          and tno like #{tno}
          and depart like #{depart};
    </select>
    <select id="selectByConditionMap" resultType="com.pojo.teachers">
        select *
        from teachers
        where start = #{start}
          and tno like #{tno}
          and depart like #{depart};
    </select>

    <!--
    查询-多条件-动态条件查询
        *if:条件判断
            *test:逻辑表达式
        *问题:
            * 恒等式
    -->
    <select id="ChoicesSelectByConditionMap" resultType="com.pojo.teachers">
        select *
        from teachers
        <where>
            <if test="start != null">
                and start = #{start}
            </if>
            <if test="tno != null and tno != '' ">
                and tno like #{tno}
            </if>
            <if test="depart != null and depart != '' ">
                and depart like #{depart};
            </if>
        </where>
    </select>

    <!--
    查询-单挑件-动态查询语句
        从多个条件中选择一个
        choose(when(类似于case),otherwise(类似于default)):选择,类似于Java中的Switch语句
    -->
    <select id="SelectByConditionSingle" resultType="com.pojo.teachers">
        select * from teachers where
        <choose>    <!--相当于于Switch -->
            <when test="start != null"> <!--类似于case -->
                start = #{start}
            </when>
            <when test="tno != null and tno != '' "> <!--类似于case -->
                tno like #{tno}
            </when>
            <when test="depart != null and depart != '' "> <!--类似于case -->
                depart like #{depart}
            </when>
            <otherwise>
                1=1
            </otherwise>
        </choose>
    </select>
    <!--    返回添加数据的主键
                只需要设置两个属性
                    1.useGeneratedKeys设为true(默认为false)
                    2.keyProperty设为要返回的列名称即可
    -->
    <insert id="add" useGeneratedKeys="true" keyProperty="tno">
        insert into teachers(tno, tname, tsex, tbirthday, prof, depart, start)
        values (#{tno}, #{tname}, #{tsex}, #{tbirthday}, #{prof}, #{depart}, #{start});
    </insert>
    <update id="update">
        update teachers
        set tname  = #{tname},
            depart = #{depart},
            start  = #{start}
        where tno = #{tno};
    </update>
    <!--动态sql修改
    用户传给什么样的数据就修改什么样的数据,不修改的数据保持原封不动
    -->
    <update id="AutoUpdate">
        update teachers
        <set>
            <if test="tsex != null and tsex != '' ">
                tsex = #{tsex},
            </if>
            <if test="tbirthday != null and tbirthday != '' ">
                tbirthday = #{tbirthday},
            </if>
            <if test="prof != null and prof != '' ">
                tname = #{prof},
            </if>
            <if test="tname != null and tname != '' ">
                tname = #{tname},
            </if>
            <if test="depart != null and depart != '' ">
                depart = #{depart},
            </if>
            <if test="start != null ">
                start = #{start}
            </if>
        </set>
        where tno = #{tno};
    </update>

    <!--
        删除   删除一个
    -->
    <delete id="deleteByTno">
        delete
        from teachers
        where tno = #{tno};
    </delete>

    <!--
        删除   删除多个(批量删除)
        collection 是要遍历哪个集合或者数组
        item 是遍历出的每一个元素
        1.编写接口方法:Mapper接口
            参数:tno数组
            结果:void
        2.编写sql语句:sql映射文件
        3.执行方法,测试
    -->
    <!--
        mybatis会将数组参数,封装一个Map集合。 collection="array"
           *默认:array = 数组 (会将咱们自己设定数组名改为array)
           *实在想用的话,使用@Parm注解改变Map集合的默认Key的名称
                例如 @Param("tnos") String[] tnos 此时
                        collection="tnos" 就是直接使用咱们自己设定好的
    -->
    <delete id="deleteByTnos">
        delete from teachers where tno in
        <foreach collection="array" item="tno" separator="," open="(" close=")">
            #{tno}
        </foreach>
    </delete>


</mapper>

然后看一下teachersMapper接口

package com.Mapper;


import com.pojo.teachers;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
public interface teachersMapper {
    /**
     * 查询所有
     */
     List<teachers> selectAll();

    /**
     * 根据教工号查询一个老师的所有信息
     */
    teachers selectOne(String tno);

    /**
     * 条件查询
     *  *参数接受
     *      1.散装参数:如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")
     *      2.对象参数:对象属性名称要和参数占位符名称一致
     *      3.map集合参数
     * @param start
     * @param tname
     * @param prof
     * @return
     */
    List<teachers> selectByCondition(@Param("start")int start,@Param("tno")String tno,@Param("depart")String depart);


    teachers selectByConditionObj(teachers tes);

    List<teachers> selectByConditionMap(Map map);


    List<teachers> ChoicesSelectByConditionMap(Map map);

    /**
     * 单挑件动态查询
     * @param tes
     * @return
     */
    List<teachers> SelectByConditionSingle(teachers tes);

    /**
     * 添加
     */
    void add(teachers tes);

    /**
     * 修改
     */
    void update(teachers teachers);

    /**
     * 动态修改
     */
    void AutoUpdate(teachers tes);

    /**
     * 删除   删除一个
     */
    void deleteByTno(String tno);

    /**
     * 删除 批量删除
     */
    void deleteByTnos(String[] tnos);
}

下面看下TestResult包下的TestMyabtis源码

package TestResult;

import Util.initLogRecord;
import com.Mapper.studentsMapper;
import com.Mapper.teachersMapper;
import com.pojo.students;
import com.pojo.teachers;
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 org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

public class TestMybatis {
    /**
     * 使用Mapper代理方式
     * 1.定义与sql映射文件同名的Mapper接口,斌且将Mapper接口和sql映射文件放置在同一目录下
     * 2.设置sql映射文件的namespace属性为Mapper接口全限定名
     * 3.在Mapper接口中定义方法,方法名就是sql映射文件中sql语句的id,并保持参数类型和返回值类型一致
     * 4.编码
     * 1.通过SqlSession的getMapper方法获取Mapper接口的代理对象
     * 2.体哦啊用对应方法完成sql的执行
     *
     * @throws IOException
     */
    @Test
    public void selectAll() throws IOException {
        initLogRecord.initLog();
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        studentsMapper mapper = sqlSession.getMapper(studentsMapper.class);
        List<students> students = mapper.selectAll();
        for (com.pojo.students student : students) {
            System.out.println(student);
        }
    }

    /**
     * 查询教师所有信息
     * @throws IOException
     */
    @Test
    public void TeachersSelectAll() throws IOException {
        initLogRecord.initLog();
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.获取Mapper接口的代理对象
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);

        //5.执行方法
        List<teachers> teachers = mapper.selectAll();

        for (com.pojo.teachers teacher : teachers) {
            System.out.println(teacher);
        }

        //释放资源
        sqlSession.close();
    }

    /**
     * 根据教师教工号,查询该教工号对应的所有信息
     */
    @Test
    public void TeachersSelectTno() throws IOException {
        initLogRecord.initLog();
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.获取Mapper接口的代理对象
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        teachers teachers = mapper.selectOne("804");
        System.out.println(teachers);
    }

    /**
     * 1.散装参数:如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")
     * @throws IOException
     */
    @Test
    public void TeachersSelectCondition() throws IOException {
        initLogRecord.initLog();
        //接受参数
        int start = 1;
        String tno = "8";
        String depart = "机";

        //处理参数
        tno = "%" + tno + "%";
        depart = "%" + depart + "%";
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.获取Mapper接口的代理对象
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        List<teachers> teachers = mapper.selectByCondition(start, tno, depart);
        for (com.pojo.teachers teacher : teachers) {
            System.out.println(teacher);
        }
    }

    /**
     * 2.对象参数:对象属性名称要和参数占位符名称一致
     * @throws IOException
     */
    @Test
    public void TeachersSelectConditionObj() throws IOException {
        initLogRecord.initLog();
        //接受参数
        int start = 1;
        String tno = "8";
        String depart = "机";
        //处理参数
        tno = "%" + tno + "%";
        depart = "%" + depart + "%";
        //封装对象
        teachers teachers1 = new teachers();
        teachers1.setStart(start);
        teachers1.setTno(tno);
        teachers1.setDepart(depart);
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.获取Mapper接口的代理对象
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        teachers teachers = mapper.selectByConditionObj(teachers1);
        System.out.println(teachers);
    }

    /**
     *  动态选择查询
     *  可以没有(查询的是整张表)
     *  当有多个可选择参数是
     *          传入你指定的参数,可以是其中的一部分,也可是全部   然后封装到map集合当中
     *
     * @throws IOException
     */
    @Test
    public void ChoicesSelectByConditionMap() throws IOException {
        initLogRecord.initLog();
        //接受参数
        int start = 1;
        String tno = "8";
        String depart = "机";
        //处理参数
        tno = "%" + tno + "%";
        depart = "%" + depart + "%";
        HashMap hashMap = new HashMap();
       // hashMap.put("start",start);
        //hashMap.put("tno",tno);
        //hashMap.put("depart",depart);
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.获取Mapper接口的代理对象
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
//        List<teachers> teachers = mapper.selectByConditionMap(hashMap);
//        System.out.println(teachers);
        List<teachers> teachers = mapper.ChoicesSelectByConditionMap(hashMap);
        System.out.println(teachers);
    }

    /**
     *      动态查询
     *     可以不传参数,查询的是整张表的数据
     *     传入指定1个或着多个参数,查询的就是指定条件的数据
     * @throws IOException
     */
    @Test
    public void SelectByConditionSingle() throws IOException {
        initLogRecord.initLog();
        //接受参数
        int start = 1;
        String tno = "8";
        String depart = "机";
        //处理参数
        tno = "%" + tno + "%";
        depart = "%" + depart + "%";
        teachers teachers1 = new teachers();
        teachers1.setStart(start);
        teachers1.setTno(tno);
        //teachers1.setDepart(depart);
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.获取Mapper接口的代理对象
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
//        List<teachers> teachers = mapper.selectByConditionMap(hashMap);
//        System.out.println(teachers);
        List<teachers> teachers = mapper.SelectByConditionSingle(teachers1);
        System.out.println(teachers);
    }

    /**
     * 添加一个教师数据
     * @throws IOException
     */
    @Test
    public void TestAdd() throws IOException {
        initLogRecord.initLog();
        //接受参数
        String tno = "806";
        String tname = "小明";
        String tsex = "男";
        String tbirthday = "1988-8-6";
        String prof = "讲师";
        String depart = "电子工程系";
        Integer start = 0;
        teachers teachers = new teachers();
        teachers.setTno(tno);
        teachers.setTname(tname);
        teachers.setTsex(tsex);
        teachers.setTbirthday(tbirthday);
        teachers.setProf(prof);
        teachers.setDepart(depart);
        teachers.setStart(start);
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession(false);//true为自动提交事务
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        com.pojo.teachers tes = teachers;
        mapper.add(tes);
        sqlSession.commit();
        System.out.println(tes);
        sqlSession.close();
    }

    /**
     * 修改
     *      通过教工号修改指定的教工信息
     */
    @Test
    public void TestUpdate() throws IOException {
        initLogRecord.initLog();
        //接受参数
        String tno = "806";
        String tname = "小张";
        String depart = "计算机系";
        Integer start = 1;
        teachers teachers = new teachers();
        teachers.setTno(tno);
        teachers.setTname(tname);
        teachers.setDepart(depart);
        teachers.setStart(start);
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession(false);//true为自动提交事务
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        com.pojo.teachers tes = teachers;
        mapper.update(teachers);
        sqlSession.commit();
        System.out.println(tes);
        sqlSession.close();
    }

    /**
     * 动态sql修改
     *      主键教工号必须要传入,其余的可以选则传入,然后进行修改
     * @throws IOException
     */
    @Test
    public void TestAutoUpdate() throws IOException {
        initLogRecord.initLog();
        //接受参数
        String tno = "806";
        String tname = "小红";
       // String depart = "计算机系";
        Integer start = 1;
        teachers teachers = new teachers();
        teachers.setTno(tno);
        teachers.setTname(tname);
        //teachers.setDepart(depart);
        teachers.setStart(start);
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession(false);//true为自动提交事务
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        com.pojo.teachers tes = teachers;
        mapper.AutoUpdate(teachers);
        sqlSession.commit();
        System.out.println(tes);
        sqlSession.close();
    }

    /**
     * 删除指定教工号的信息
     * @throws IOException
     */
    @Test
    public void TestDeleteByTno() throws IOException {
        initLogRecord.initLog();
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession(false);//true为自动提交事务
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        mapper.deleteByTno("806");
        sqlSession.commit();
    }

    /**
     * 批量删除指定教工号的信息
     */
    @Test
    public void TestDeleteByTnos() throws IOException {
        initLogRecord.initLog();
        //传入参数
        String [] tnos = {"804","806"};
        //1.读取mybatis的核心配置文件
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.通过配置信息获取一个SqlSessionFactory
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
        //3.通过工厂获取一个sqlSession对象
        SqlSession sqlSession = build.openSession(false);//true为自动提交事务
        teachersMapper mapper = sqlSession.getMapper(teachersMapper.class);
        mapper.deleteByTnos(tnos);
        sqlSession.commit();
    }
}

结果就不展示了,最后最重要一点,在修改,增加,删除时要提交事务,默认事务是手动提交的,如果想自动提交只需要build.openSession(),在括号中设为true即可,默认为false。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值