第十章   MyBatis入门
10.1 MyBatis入门    
    优点:简单且功能强大、能够完全控制SQL语句、容易维护和修改
    缺点:移植性不好
    使用步骤:
        1、下载所需jar包
        2、部署项目
        3、编写配置文件(mybatis-config.xml)
            <?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>
              <environments default="development">
                <environment id="development">
                  <transactionManager type="JDBC"/>
                  <dataSource type="POOLED">
                    <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                    <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcldb"/>
                    <property name="username" value="scott"/>
                    <property name="password" value="orcl"/>
                  </dataSource>
                </environment>
              </environments>
              <mappers>
                <mapper resource="com/dao/EmpDaoMapper.xml"/>
              </mappers>
            </configuration>    
        4、创建持久化类和数据库接口
        5、创建SQL映射文件(xxx.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.dao.EmpDao">    
        <!-- 查询SQL语句  -->
            <select id="countAll" resultType="int">
            SELECT COUNT(*) FROM EMP
            </select>
        </mapper>
        6、创建数据库接口的实现类
        7、编写测试类进行测试
10.2 使用MyBatis实现持久化操作
    10.2.1 条件查询
        例:根据员工编号获取员工信息
            EmpDaoMapper.xml
                <select id="findEmpByEmpNo" parameterType="int" resultType="com.entity.Emp">
                SELECT * FROM EMP WHERE empno=#{empno}
                </select>
        select元素下属性
            <select
            id="selectEmp"
            parameterType="int"    
            parameterMap="deprecated"      //引用外部parameterMap将内部参数和parameterType做映射
            resultType="com.entity.Emp"   //查询语句返回结果类型的完全限定名或别名
            resultMap="empResultMap"      //命名引用外部resultMap
            flushCache="false"              //若为true,执行语句调用后都会到期缓存被清空
            useCache="true"                  //若为true,导致执行结果被缓存,默认为true
            timeout="10000"                  //设置驱动程序等待数据库返回的超时时间,超时会报异常
            fetchSize="256"                  //设置驱动程序每次批量返回的结果行数
            statementType="PREPARED"      //STATEMENT、PREPARED、CALLABLE的一种默认为PREPARED
            resultSetType="FORWARD_ONLY"  //FORWARO_ONLY|SCROLL_SENSITIVE|SCROLL_INSENSITIVE的一种,无默认
            >
            </select>
        1、使用selectOne()方法
            例:try {
                    //省略获取SQLSession的过程
                    session=factory.openSession();
                    iCount=session.selectOne("com.dao.EmpDao.countAll");
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    session.close();
                }
        2、使用session.getMapper()方法
            例:try {
                    //省略获取SQLSession的过程
                    session=factory.openSession();
                    EmpDao empdao=session.getMapper(EmpDao.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    session.close();
                }
    10.2.2 使用resultMap实现结果映射
        。。。
    10.2.3 使用MyBatis实现数据表的增删改
        <!-- 增  -->
        <insert id="insertEmp" parameterType="com.entity.Emp">
        insert into EMP VALUES
        (#{empno},#{ename},#{job},#{mgr},#{hiredate},#{sal},#{comm},#{deptno})
        </insert>
        <!-- 删  -->
        <delete id="deleteEmp" parameterType="com.entity.Emp">
            delete from EMP where empno=#{empno}
        </delete>
        <!-- 改  -->
        <update id="updateEmp" parameterType="com.entity.Emp">
            update EMP set ename=#{ename} where empno=#{empno}
        </update>
        实现类:
            //增
                try {
                    //省略获取SQLSession的过程
                    session.insert("com.dao.EmpDao.insertEmp",emp);
                    session.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    session.close();
                }
            //删
                try {
                    //省略获取SQLSession的过程
                    session.delete("com.dao.EmpDao.deleteEmp",empNo);
                    session.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    session.close();
                }
            //改
                try {
                    //省略获取SQLSession的过程
                    session.update("com.dao.EmpDao.updateEmp",emp);
                    session.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    session.close();
                }
10.3 使用动态SQL完成复杂操作
    10.3.1 使用动态SQL完成多条件查询
        if
        例:<select id="selectEmpByIf" parameterType="com.entity.Emp" resultMap="empResultMap">
            SELECT * FROM EMP where 1=1
            <if test="deptno != null">
                amd deptno=#{deptno}
            </if>
            <if test="ename != null">
                amd ename=#{ename}
            </if>
            </select>
        choose(when,otherwise)
        例:<select id="findEmpByChoose" parameterType="com.entity.Emp" resultMap="empResultMap">
            SELECT * FROM EMP WHERE 1=1
            <choose>
                <when test="deptno != null">
                    and deptno=#{deptno}
                </when>
                <when test="ename != null">
                    and ename=#{ename}
                </when>
                <otherwise>
                    and hiredate > #{#hiredate}
                </otherwise>
            </choose>
            </select>
        where
        例:<select id="findEmpBywhere" parameterType="com.entity.Emp" resultMap="empResultMap">
            SELECT * FROM EMP
                <where>
                    <if test="deptno != null">
                        and deptno=#{deptno}
                    </if>
                    <if test="ename != null">
                        and ename=#{ename}
                    </if>
                </where>
            </select>
        set
        例:<update id="updateEmpSet" parameterType="com.entity.Emp">
            UPDATE EMP
            <set>
                <if test="ename != null">
                    ename=#{ename},
                </if>
                <if test="job != null">
                    job=#{job},
                </if>
            </set>
            where empno=#{empno}
            </update>
    10.3.2 MyBatis核心类生命周期和管理
        1、SQLSessionFactoryBuilder
        2、SqlSessionFactory
        3、SqlSession
        工具类:public class MyBatisUtil {
                private MyBatisUtil(){
                }
                    private static final String RESOURCE="mybatis-config.xml";
                    private static SqlSessionFactory sqlSessionFactory=null;
                    private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<SqlSession>();
                    static{
                        Reader reader=null;
                        try {
                            reader=Resources.getResourceAsReader(RESOURCE);
                            SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
                            sqlSessionFactory=builder.build(reader);
                        } catch (Exception e) {
                            throw new ExceptionInInitializerError("初始化MyBatis错误");
                        }
                    }
                    public static SqlSessionFactory geetSqlSessionFactory(){
                        return sqlSessionFactory;
                    }
                    public static SqlSession getSession(){
                        SqlSession session=threadLocal.get();
                        if(session != null){
                            session=(sqlSessionFactory != null)?sqlSessionFactory.openSession():null;
                            threadLocal.set(session);
                        }
                        return session;
                    }
                    public static void closeSession(){
                        SqlSession session=(SqlSession)threadLocal.get();
                        threadLocal.set(null);
                        if(session != null){
                            session.close();
                        }
                    }
                }
10.4 使用MyBatis实现员工信息管理
    10.4.1 配置缓存
        1、MyBatis的全局cache配置
            <settings>
                <setting name="cacheEnabled" value="true" />
            </settings>
        2、在Mapper XML中开启二级缓存
            <cache eviction="FIFO" flushinterval="60000" size="512" readOnly="true"/>
        
        3、单独设置cache
            开启二级缓存后如果需要对个别查询进行调整,可单独设置cache
            <select id="selectAll" resultType="Emp" useCache="true"</select>

第十章 MyBatis入门的更多相关文章

  1. MyBatis1:MyBatis入门

    MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...

  2. mybatis入门基础(二)----原始dao的开发和mapper代理开发

    承接上一篇 mybatis入门基础(一) 看过上一篇的朋友,肯定可以看出,里面的MybatisService中存在大量的重复代码,看起来不是很清楚,但第一次那样写,是为了解mybatis的执行步骤,先 ...

  3. MyBatis入门基础(一)

    一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记 ...

  4. MyBatis入门案例、增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

  5. mybatis入门_mybatis基本原理以及入门程序

    一.传统jdbc存在的问题 1.创建数据库的连接存在大量的硬编码, 2.执行statement时存在硬编码. 3.频繁的开启和关闭数据库连接,会严重影响数据库的性能,浪费数据库的资源. 4.存在大量的 ...

  6. MyBatis入门学习教程-使用MyBatis对表执行CRUD操作

    上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...

  7. MyBatis入门学习(二)

    在MyBatis入门学习(一)中我们完成了对MyBatis简要的介绍以及简单的入门小项目测试,主要完成对一个用户信息的查询.这一节我们主要来简要的介绍MyBatis框架的增删改查操作,加深对该框架的了 ...

  8. MyBatis入门学习(一)

    一.MyBatis入门简要介绍(百科) MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyB ...

  9. MyBatis入门案例 增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

随机推荐

  1. 简单却又复杂的FizzBuzz面试编程问题

    写这篇文章主要是因为偶然看到一篇关于stackoverflow公司的面经中提到了一个有趣的面试编程问题,如题所述:FizzBuzz问题.原文引用如下: “在一些公平的考验之后,我发现那些因为代码而抓狂 ...

  2. 解决VS2015 VBCSCompiler.exe 占用CPU100%的问题

    使用VS2015重复编译运行会发现系统运行缓慢甚至卡死,打开windows任务管理器可以发现CPU已经飙到了100%, VBCSCompiler.exe进程出现多个实例并且占用了大量CPU. 解决方案 ...

  3. UIImagePickerController拍照/相册/录像/本地视频

    1.导入系统库 #import <MobileCoreServices/MobileCoreServices.h> 2.遵守协议 <UIImagePickerControllerDe ...

  4. ajax上传图片

    选择文件后 ajax上传图片到后台,后台执行保存操作,返回上传的图片路径,显示到页面 需要引入ajaxfileupload.js js代码 <script type="text/jav ...

  5. subline text3常用插件介绍

    常用插件介绍:  html beautify(ctrl+shift+alt+f) 自动排版代码 Emmet 输入少量代码后摁Tab键,系统自动补全代码. AutoFileName 快速列出你想引用的文 ...

  6. 【js数据结构】栈解决佩兹糖果盒问题

    现实生活中栈的一个例子是佩兹糖果盒. 想象一下你有一盒佩兹糖果, 里面塞满了红色. 黄色和白色的糖果, 但是你不喜欢黄色的糖果. 使用栈( 有可能用到多个栈) 写一段程序, 在不改变盒内其他糖果叠放顺 ...

  7. 【原创】有关Buffer使用,让你的日志类库解决IO高并发写

    [本人原创],欢迎交流和分享技术,转载请附上如下内容: 作者:itshare [转自]http://www.cnblogs.com/itshare/ 通常我们知道,当一个日志借口被外部程序多个线程请求 ...

  8. Webpack单元测试,e2e测试

    此篇文章是续 webpack多入口文件.热更新等体验,主要说明单元测试与e2e测试的基本配置以及相关应用. 一.单元测试 实现单元测试框架的搭建.es6语法的应用.以及测试覆盖率的引入. 1. 需要安 ...

  9. Altera Stratix IV Overview

    由于要开发基于DE4平台的应用,应该要了解一下该平台的芯片情况Stratix IV 具体型号为:Stratix IV EP4SGX230KF40C2 命名规范如下 官网资料为:https://www. ...

  10. C#生成漂亮验证码完整代码类

    using System;using System.Web;using System.Drawing;using System.Security.Cryptography; namespace Dot ...