Mybatis笔记

Mybatis的特点

一、属于持久层ORM框架

​ 1.持久层:内存中的对象数据转移到数据库中的过程叫持久层

​ Mybatis、Hibernate、Spring-jpa

​ 2.ORM Object Relation Mapping 对象关系映射框架

​ 类 表

​ 属性 字段

​ 对象 记录

​ 3.半自动 自动化

​ Mybatis半自动化

​ 表需要手动进行设计
​ 提供sql
​ 依赖与数据库平台
​ 优点:学习使用简单(基与原声jdbc封装),优化灵活,适合做互联网项目

​ Hibernate 自动化ORM框架

​ 表可以通过框架自动创建
​ 省略一些基本的sql
​ 不依赖与数据库平台
​ 缺点: 学生成本高,优化难度大,适合与传统框(OA|图书管理系统…),不适合做大型互联网项
​ 目

Mybatis的环境搭建

一、新建Java项目,导入核心Java包与Mybatis依赖的jar包

​ 1.mybatis核心jar包

​ 2.mybatis依赖jar包

​ 3.数据库驱动jar包

二、Mybatis核心配置文件

​ 1.是一个xml文件,命名、位置无要求,一般命名为mybatis-config.xml,放在src下

​ 2.dtd

<!DOCTYPE configuration	 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

​ 为配置文件添加约束

​ 3.mybatis.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>
    <!-- 加载外部的properties文件 -->
    <properties resource="db.properties" />

    <!--配置别名-->
    <typeAliases>
        <package name="com.yjxxt.pojo"/> <!-- 包下所有的类默认类名,不区分大小写 -->
    </typeAliases>


    <environments default="dev">
        <!--环境的配置-->
        <environment id="dev">
            <!--事务管理 : type="JDBC" 与JDBC相同的事务管理机制-->
            <transactionManager type="JDBC"/>
            <!--数据源信息的配置 type="POOLED"选择连接池技术 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--在接口绑定方案使用的前提下: 扫描接口-->
    <mappers>
       <!-- <mapper class="com.yjxxt.mappers.EmpMapper"></mapper>  配置一个接口路径-->
        <package name="com.yjxxt.mappers"/> <!--扫描一个包下的所有接口-->
    </mappers>
</configuration>
三、Mybatis SQL映射文件

​ 1.在Mybatis中,推荐使用mappers作为包名,我们只需要写一个映射配置文件就可以,DeptMapper.xml,用于

​ 定义要执行的sql语句,同时可以设置参数|返回值结果类型

<?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.yjxxt.mappers.DeptMapper">
    <select id="queryAll" resultType="dept">
        select deptno no,dname name,loc location from dept
    </select>
</mapper>

配置文件详解

1.configuration

​ 配置文件的根元素,所有其他的元素都要在这个标签下使用(dtd文件规定)

2.environments default=“environment”
用于管理所有环境, 并可以指定默认使用那个环境,通过defualt属性来指定

3.environment
用来配置环境,id属性用于唯一标识当前环境

4.transactionManager type=“JDBC”
用户配置事务管理器

​ type属性
​ 用来指定Mybatis采用何种方式管理事务

​ JDBC : 表示采用与原生JDBC一致方式管理事务
​ MANAGED: 表示讲事务管理交给其他容器进行, Spring

5.dataSource type=“POOLED”
用于配置数据源, 设置Myabtis是否使用连接池技术,并且配置数据库的四个连接参数
type属性:
POOLED : 表示采用连接池技术
UNPOOLED: 表示每次都会开启和关闭连接, 不采用连接池技术
JNDI : 使用其他容器提供数据源

6.property
用于配置数据库连接参数 (driver,url,username,password)

7.Mappers
用于配置扫描sql映射文件

SQL映射文件

1.mapper

SQL映射文件的根元素
namespace 属性:
用于指定命名空间, mydatis通过namespace+id的方式用来定位sql语句,所以必须要指定
namespace,通过被配置为权限定路径 包名+xml文件名(不带后缀名)

2.select

用来定义查询语句 update insert delete
id 属性:
用id唯一表示当前sql语句,在当前的命名空间中唯一,不能重复 , 类型方法名
resultType 属性:
用于设定查询返回的结果的数据类型,要写类型的权限定名(包名+类名),如果返回值的是集合类型,要
定义集合的泛型类型

三个查询方法

  • selectList(“命名空间.id”) 用户查询多条数据情况,返回一个List集合, 没有查到数据返回空集合,不是
    null

  • selectOne(“命名空间.id”) 用于查询单条数据,返回一个数据, 如果没有查到返回null

  • selectMap(“命名空间.id”,key的字段名) 用于查询多条记录情况, 返回Map集合, 需要指定那个属性
    作为key, sql查询结果作为value,指定的字段值作为key, 如果查不到, 返回一个空map集合,不是null

通过properties标签实现软编码

一、src下定义配置文件db.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
username=SCOTT
password=TIGER		
二、properties标签

​ mybatis核心配置文件中添加properties标签,指定加载外部的properties文件,注意定义位置

<!-- 加载外部的properties文件 -->
<properties resource="db.properties" />
三、使用方式

​ 获取properties文件中数据时候,要通过${}的方式获取

<environments default="even">
<environment id="even">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>

typeAliases标签

用于给java类型定义别名,方便在配置文件中使用

一、使用方式

​ 1.给指定的类定义别名

​ 2.省略alias属性,表示别名为类名,不区分大小写

​ 3.可以通过package标签给整个包下的所有类定义别名,别名为类名

<!--  配置别名  -->
    <typeAliases>
<!--        <typeAlias type="com.com.yjx.pojo.Dept" />&lt;!&ndash;默认别名,不区分大小写&ndash;&gt;-->
<!--        <typeAlias type="com.com.yjx.pojo.Dept" alias="Dept"></typeAlias>&lt;!&ndash;自定义别名&ndash;&gt;-->
        <package name="com.yjx.pojo"/><!--包下所有类默认别名,不区分大小写-->
    </typeAliases>
二、mybaits的内建别名

下面是一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。

别名 映射的类型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

parameterType入参类型

​ 如果执行的是条件查询,DML,需要在调用方法的时候传递参数,此时, 可以在sql标签中通过parameterType属性指定参数的类型(别名|权限定名). 而在sql语句,通过#{}的方式获取参数

一、一个参数的查询

​ 根据id查询用户信息,当参数只有一个,#{}可以任意填写匹配参数

<select id="queryById" parameterType="int" resultType="com.yjx.pojo.Dept" >
    select * from dept where deptno = #{deptno}
</select>
二、多个参数的查询

​ 多个参数传递时, 由于sqlSession中提供的查询方法,只允许传递一个sql参数, 因此可以对多个参数进行
封装,可以对象,集合,数组…

<select id="queryDeptByBean" parameterType="com.yjx.pojo.Dept" resultType="com.yjx.pojo.Dept">    select * from dept where dname = #{dname} and deptno = #{deptno}</select><select id="queryDeptByList" parameterType="list" resultType="com.yjx.pojo.Dept">        select * from dept where dname = #{dname} and deptno = #{deptno}</select>
三、入参类型

​ paramType:基本数据类型(四类八种)包装类、String、Date、Javabean、Map、List、数组

工具类的封装

package com.yjx.utils;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.IOException;public class SessionUtils {    private static SqlSessionFactory factory = null;    static {        //加载核心配置文件        //获取SqlSessionFactory实例        try {            factory = new  SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));        } catch (IOException e) {            e.printStackTrace();        }    }    public static SqlSession getSession(){        SqlSession sqlSession = null;        if (factory != null) {            sqlSession = factory.openSession(true);        }        return sqlSession;    }}

事务(Transaction)

事务是数据库操作的最小单位,有着ACID的特性,应该保证一个事务下的多条SQL语句要么都成功,要
么都失败.
Mybatis中配置了事务管理器,type属性设置JDBC,表示Mybatis采用和原生JDBC相同的事务管理机

在Myabatis执行操作的开始,将自动提交功能关闭了,需要我们在执行DML操作时候,手动提交设置|
设置自动提交

手动提交:

session.commit(); //事务提交

设置自动提交事务:

public static SqlSession getSession() {SqlSession session =null;if(factory!=null) {//session = factory.openSession(); //默认手动提交事务session = factory.openSession(true); //自动提交}return session;}

增删改操作

SQL映射文件:
<delete id="deleteEmp" parameterType="int">    delete from emp where empno = #{empno}</delete><delete id="deleteByList" parameterType="list">    delete from emp where empno in (    <foreach collection="list" item="item" separator=",">        #{item}    </foreach>    )</delete><update id="updateSomeName" parameterType="list">    <foreach collection="list" item="item" open="begin" close=";end;"             separator=";">        update emp set ename = #{item.ename} where empno = #{item.empno}    </foreach></update><insert id="insertSomEmp" parameterType="list">    insert into emp(empno,ename,sal)    <foreach collection="list" item="item" separator="union">        select #{item.empno},#{item.ename},#{item.sal} from dual    </foreach></insert>
Java测试类:
public class UserTest02 {            //删除方法            @Test            public void testDelete() {                SqlSession session = MybatisUtils.getSession();                int rows = session.update("com.xxxx.mappers.UserMapper2.deleteUser",                        100);                if (rows > 0) {                    System.out.println("SECCESS!!!");                } else {                    System.out.println("FAILED!!!");                }                    //会话关闭                14. resultType结果类型                基本数据类型(包装类) String Date JavaBean List Map List -Map                session.close();            }            //修改方法            @Test            public void testUpdate() {                SqlSession session = MybatisUtils.getSession();                User user = new User();                user.setId(100);                user.setUserpwd(9876);                int rows = session.update("com.xxxx.mappers.UserMapper2.updateUser",                        user);                if (rows > 0) {                    System.out.println("SECCESS!!!");                } else {                    System.out.println("FAILED!!!");                }                    //会话关闭                session.close();            }            //插入方法            @Test            public void testInsert() {                SqlSession session = MybatisUtils.getSession();                User user = new User();                user.setUsername("zhangsan");                user.setUserpwd(789);                    //插入方法                int rows = session.insert("com.xxxx.mappers.UserMapper2.insertUser",                        user);                    //影响行数判断                if (rows > 0) {                    System.out.println("SECCESS!!!");                    //session.commit(); //事务提交                } else {                    System.out.println("FAILED!!!");                //session.rollback();                }                //会话关闭                session.close();            }        }

resultType结果类型

​ 基本数据类型(包装类) String Date JavaBean List Map List-Map

接口绑定方案***

Myabtis中,提供了一套接口绑定方案,程序员可以提供一个接口,然后提供一个与接口所对应的
mapper.xml文件
Myabaits会自动讲接口与xml文件进行绑定,实际上就是Mybatis互根据接口和对应的xml文件创建一个接
口的实现类,换言之,就是可以得到接口类型的一个对象,方便方法的调用

一、实现方式
1.定义接口
public interface DeptMapper {    List<Dept> queryAll();}
2.映射文件
<?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"><!-- resultType : 默认自动映射机制  resultMap : 手动映射机制--><mapper namespace="com.yjxxt.mappers.DeptMapper">    <select id="queryAll" resultType="dept">        select deptno no,dname name,loc location from dept    </select></mapper>
3、 在核心配置文件中扫描接口

​ 1) 扫描单个接口,可以使用mapper标签的class属性

<!-- mapper 配置扫描接口 --><mappers><mapper class="com.xxxx.mapper.UserMapper"/>  <!--配置某个接口 --></mappers>

​ 2) 扫描多个接口,可以简化配置,使用package标签,表示扫描对应包下的所有接口

<!-- mapper 配置扫描接口 --><mappers><package name="com.xxxx.mapper"/></mappers>
4、使用
@Testpublic void test01(){    SqlSession session = SessionUtils.getSession();    DeptMapper mapper = session.getMapper(DeptMapper.class);    List<Dept> depts = mapper.queryAll();    depts.forEach(System.out::println);}
二、通过接口绑定解决多参数传递问题
方式一

​ a)接口中定义方法

User selByUP(String username, String password);

​ b) 映射文件中提供对应的标签. 此时, SQL 语句中获取方式有两种, 通过#{arg+数字}或#{param+数字}的方式.

<select id="selByUP" resultType="user">       select * from t_user where username=#{param1} and password=#{param2}</select>
方式二

​ a) 接口中定义方法, 参数中使用@Param 注解设定参数名用于在 SQL 语句中使用.

User selByUP(@Param("username") String username, @Param("password")String password);

​ b) 映射文件中提供对应的标签. 此时, SQL 语句中获取方式有两种, 通过#{参数名称}或#{param+数字}的方式.

<select id="selByUP" resultType="user">    select * from t_user where username=#{username} and    password=#{password}</select>

接口代理开发(CRUD)

一、基本CRUD操作
<select id="queryEmpByNameSal" resultType="emp">    select * from emp where ename = #{ename} and sal = #{sal}</select><insert id="insertEmp" parameterType="emp">    insert into emp(empno,ename,sal) values(seq_emp_empno.nextval,#{ename},#{sal})</insert><delete id="deleteEmp" parameterType="int">    delete from emp where empno = #{empno}</delete>
二、批量操作
<delete id="deleteByList" parameterType="list">    delete from emp where empno in (    <foreach collection="list" item="item" separator=",">        #{item}    </foreach>    )</delete>    <update id="updateSomeName" parameterType="list">        <foreach collection="list" item="item" open="begin" close=";end;"                 separator=";">            update emp set ename = #{item.ename} where empno = #{item.empno}        </foreach>    </update>    <insert id="insertSomEmp" parameterType="list">        insert into emp(empno,ename,sal)        <foreach collection="list" item="item" separator="union">            select #{item.empno},#{item.ename},#{item.sal} from dual        </foreach>    </insert>

动态 SQL

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同

条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个
列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显
著地提升了这一特性的易用性。

一、if

​ 用于进行条件判断, test 属性用于指定判断条件. 为了拼接条件, 在 SQL 语句后强行添加 1=1 的恒成立条件

<select id="sel" resultType="user">    select * from t_user where 1=1    <if test="username != null and username != ''"> and username=#{username}    </if>    <if test="password != null and password != ''"> and password=#{password}    </if></select>
二、where

​ 用于管理 where 子句. 有如下功能:

​ 1.如果没有条件, 不会生成 where 关键字

​ 2.如果有条件, 会自动添加 where 关键字

​ 3.如果第一个条件中有 and, 去除之

<select id="sel" resultType="user">    select * from t_user    <where>        <if test="username != null and username != ''"> and username=#{username}        </if>        <if test="password != null and password != ''"> and password=#{password}        </if>    </where></select>
三、choose…when…otherwise

​ 这是一套标签, 功能类似于 switch…case…

<select id="sel" resultType="user">    select * from t_user    <where>        <choose>            <when test="username != null and username != ''">               and username = #{username}                </when>            <when test="password != null and password != ''">               and password = #{password}               </when>            <otherwise> and 1=1 </otherwise>        </choose>    </where></select>
四、set

​ 用于维护 update 语句中的 set 子句. 功能如下:

​ 1.满足条件时, 会自动添加 set 关键字

​ 2.会去除 set 子句中多余的逗号

​ 3.不满足条件时, 不会生成 set 关键字

<update id="updUser" parameterType="user">update t_user<set>id=#{id},<!-- 防止所有条件不成立时的语法错误 --><if test="username != null and username != ''">username=#{username},</if><if test="password != null and password != ''">     password=#{password},    </if></set>where id=#{id}</update>
五、trim

用于在前后添加或删除一些内容

  1. prefix, 在前面添加内容

  2. prefixOverrides, 从前面去除内容

  3. suffix, 向后面添加内容

  4. suffixOverrides, 从后面去除内容

    <update id="updateEmp">
        update emp
        <trim prefix="set" suffixOverrides=",">
            empno=#{empno},<!-- 防止所有条件不成立时的语法错误 -->
            <if test="ename!=null and ename!=''">
                ename = #{ename},
            </if>
            <if test="sal!=null and sal!=0">
                sal=#{sal},
            </if>
        </trim>
        where empno=#{empno}
    </update>
    
六、bind

​ 用于对数据进行再加工, 用于模糊查询

<select id="sel" resultType="user">
    select * from t_user
    <where>
        <if test="username!=null and username!=''">
            <bind name="username" value="'%' + username + '%'" />
            and username like #{username}
        </if>
    </where>
</select>
七、foreach
		用于在 SQL 语句中遍历集合参数, 在 in 查询中使用
  1. collection: 待遍历的集合

  2. open: 设置开始符号

  3. item: 迭代变量

  4. separator: 项目分隔符

  5. close: 设置结束符

    <select id="selIn" parameterType="list" resultType="user">
        select * from t_user where id in
        <foreach collection="list" open="(" separator="," close=")"
                 item="item"> #{item} </foreach>
    </select>
    
八、sql…include

sql用于提取 SQL 语句, include用于引用 SQL 语句

<select id="selIn" parameterType="list" resultType="user">
    select
    <include refid="mySql" />
    from t_user where id in
    <foreach collection="list" open="(" separator="," close=")"
             item="item"> #{item}
    </foreach>
</select>

列名和属性名不一致问题

如果查询时使用 resultType 属性, 表示采用 MyBatis 的Auto-Mapping(自动映射)机制, 即相同的列名和
属性名会自动匹配. 因此, 当数据库表的列名和类的属性名不一致时, 会导致查不到数据. 解决该问题可以
有两种方式:

列别名

查询时, 可以通过列别名的方式将列名和属性名保持一致,继续使用自动映射, 从而解决该问题. 但是较为
麻烦.

使用resultMap

resultMap用于自定义映射关系, 可以由程序员自主制定列名和属性名的映射关系. 一旦使用 resultMap,
表示不再采用自动映射机制.

关系映射查询

数据库中表与表之间的关系:
一对一 (人->身份证)
一对多 (夏令营->学生)
多对一 (学生->班级)
多对多 (学生->课程)

resultMap 的关联方式实现多表查询(一对一|多对一)
  1. 在 StudentMapper.xml 中定义多表连接查询 SQL 语句, 一次性查到需要的所有数据, 包括对应班级
    的信息.
  2. 通过resultMap标签定义映射关系, 并通过association标签指定对象属性的映射关系. 可以把
    association标签看成一个resultMap标签使用. javaType 属性表示当前对象, 可以写全限定路径或
    别名.
<resultMap id="resultMap01" type="Emp">
    <id column="empno"  property="empno"></id>
    <result column="deptno" property="deptno"></result>
    <result column="sal" property="sal"></result>
    <result column="comm" property="comm"></result>
    <result column="hiredate" property="hiredate"></result>
    <association property="dept" javaType="Dept">
        <id column="deptno" property="no"></id>
        <result column="dname" property="name"></result>
        <result column="loc" property="location"></result>
    </association>
</resultMap>
resultMap 的关联方式实现多表查询(一对 多)
  1. 在 ClazzMapper.xml 中定义多表连接查询 SQL 语句, 一次性查到需要的所有数据, 包括对应学生的
    信息.
  2. 通过resultMap定义映射关系, 并通过collection标签指定集合属性泛型的映射关系. 可以collection
    标签看成一个resultMap标签使用. ofType 属性表示集合的泛型, 可以写全限定路径或别名.
<resultMap id="map1" type="Dept">
    <!--主键字段映射关系-->
    <id column="deptno" property="no"></id>
    <!--非主键字段映射关系-->
    <result column="dname" property="name"></result>
    <result column="loc" property="location"></result>

    <!--当类中的属性为集合使用collection-->
    <collection property="emps" javaType="list"
                ofType="Emp">
        <id property="empno" column="empno" />
        <result property="ename" column="ename" />
        <result property="sal" column="sal" />
        <result property="deptno" column="deptno" />
    </collection>
</resultMap>

Log4J日志

Log4J简介
 日志是应用软件中不可缺少的部分,Apache的开源项目log4j是一个功能强大的日志组件,提供方便的日

志记录。在apache网站:jakarta.apache.org/log4j 可以免费下载到Log4j最新版本的软件包。

日志级别:

​ DEBUG(人为调试信息)、INFO(普通信息)、WARN(警告)、ERROR(错误)和FATAL(系统错误)这五个级别是有顺序的,DEBUG < INFO < WARN < ERROR < FATAL,分别用来指定这条日志信息的重要程度,明白这一点很重要,Log4j有一个规则:只输出级别不低于设定级别的日志信息,假设Loggers级别设定为INFO,则INFO、WARN、ERROR和FATAL级别的日志信息都会输出,而级别比INFO低的DEBUG则不会输出

Log4J使用

​ 1.导包

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k19WB0cl-1630159843368)(Mybatis.assets/image-20210823205113140.png)]

​ 2.写配置

# Set root category priority to INFO and its only appender to CONSOLE. 
 log4j.rootCategory=INFO, CONSOLE 
#log4j.rootCategory=INFO, CONSOLE, LOGFILE
   
# CONSOLE is set to be a ConsoleAppender using a PatternLayout. 
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 
log4j.appender.CONSOLE.layout.ConversionPattern= %m%n

#单独设置sql语句的输出级别为DEBUG级别
#方法级别设置
#log4j.logger.com.yjx.mappers.DeptMapper.queryAll=DEBUG
#类级别设置
#log4j.logger.com.yjx.mappers.DeptMapper=DEBUG
#包级别设置
log4j.logger.com.yjx.mappers=DEBUG

# LOGFILE is set to be a File appender using a PatternLayout. 
log4j.appender.LOGFILE=org.apache.log4j.FileAppender 
log4j.appender.LOGFILE.File=D:/log4j_document/ideacode05_document/test.log
log4j.appender.LOGFILE.Append=true 
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout 
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n

Mybatis对Log4J的支持

​ 1.通过setting标签开启logj的支持

​ 在Mybatis核心配置文件中,settings用于设置 MyBatis 在运行时的行为方式, 例如:缓存, 延迟加载, 日志等.

<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>

局部调整日志级别, 定制日志的输出
#单独设置sql语句的输出级别为DEBUG级别
#方法级别设置
#log4j.logger.com.yjx.mappers.DeptMapper.queryAll=DEBUG
#类级别设置
#log4j.logger.com.yjx.mappers.DeptMapper=DEBUG
#包级别设置
log4j.logger.com.yjx.mappers=DEBUG

Mybatis缓存机制

一、一级缓存
  1. 默认开启. 线程级别的缓存, SqlSession 的缓存;

  2. 在一个 SqlSession 生命周期中有效. SqlSession 关闭,缓存清空;

  3. 在同一个 SqlSession 中, Mybatis 会把执行的方法和参数通过算法生成缓存的键值, 将键值和结果
    存放在一个 Map 中, 如果后续的键值一样, 则直接从 Map 中获取数据;

  4. 不同的 SqlSession 之间的缓存是相互隔离的;

  5. 用一个 SqlSession, 可以通过配置使得在查询前清空缓存;flushCache=“true”

  6. 任何的 UPDATE, INSERT, DELETE 语句都会清空缓存。

二、二级缓存
  1. 进程级别的缓存, SqlSessionFactory 的缓存
  2. 在一个SqlSessionFactory生命周期中有效. 可以在多个SqlSession 生命周期中共享.
  3. 默认关闭, 需要使用的时候, 要为某个命名空间开启二级缓存(在 mapper.xml 中配置cache).
  4. 由于在更新时会刷新缓存, 因此需要注意使用场合:查询频率很高, 更新频率很低时使用, 即经
    常使用 select, 相对较少使用delete, insert, update。
  5. 缓存是以 namespace 为单位的,不同 namespace 下的操作互不影响。但刷新缓存是刷新整个
    namespace 的缓存, 也就是你 update 了一个, 则整个缓存都刷新了。
  6. 最好在 「只有单表操作」 的表的 namespace 使用缓存, 而且对该表的操作都在这个 namespace
    中。 否则可能会出现数据不一致的情况。
二级缓存应用场景:

​ 对于访问多的查询请求并且用户对查询结果实时性要求不高的情况下,可采用mybatis二级缓存,降低
数据库访问量,提高访问速度,如电话账单查询
根据需求设置相应的flushInterval:刷新间隔时间,比如三十分钟,24小时等。。

注意

​ 1、使用二级缓存时JavaBean需要实现序列化:为了将缓存的数据取出,执行反序列化的操作,需要实现序列化接口;因为二级缓存的存储介质是多种多样的,可能在内存中也可能在硬盘中,所以取出缓存中的数据需要反序列化

​ 2、需要通过session.close()方法将数据存储到二级缓存中并关闭会话

​ 3、可以在sql映射文件的sql语句中声明flushCache=“true” 开启或关闭自动刷新一级缓存,或者声明useCache="true"来开启或关闭自动刷新二级缓存,可以在<cache />标签中声明flushInterval属性指定刷新间隔的毫秒数

​ 4、二级缓存不适合用于查询商品的最新数据,因为二级缓存是以mapper为单位,一个商品修改,其他商品在二级缓存中都会被刷新

​ 5、一级缓存的失效条件:

​ 一次查询完成后,关闭当前会话

​ 两次查询之间执行增删改操作

​ 在sql映射文件中的sql语句标签中声明flushCache="true"属性

​ 二级缓存失效条件:

​ 查询完成之后,不关闭会话

​ 两次查询之间执行增删改操作

​ 在sql映射文件中的sql语句标签中声明useCache="false"

注解开发

Mybatis中注解的作用

​ 使用注解一般用于简化配置文件. 但是, 注解有时候也不是很友好(有时候反而更麻烦), 例如动态 SQL等,所
​ 以注解和配置文件可以配合使用

Mybatis中常用的注解

​ 1.CRUD注解

​ @Select: 类似于select标签
​ @Insert: 类似于insert标签
​ @Update: 类似于update标签
​ @Delete: 类似于delete标签

​ 2.其他注解

​ @Results: 类似于resultMap标签
​ @Result: 类似<resultMap的子标签
​ @One: 类似于association标签
​ @Many: 类似于collection标签

public interface StudentMapper {
@Select("select * from t_student")
@Results(
		value = { @Result(column="id", property="id", id=true),
		@Result(column="name", property="name"),
		@Result(column="age", property="age"),
        @Result(column="gender", property="gender"),
        @Result(column="cid", property="cid"),
		@Result(property="clazz",
		one=@One(select="com.xxxx.mapper.ClazzMapper.selById"),
		column="cid")
		}
	)
	List<Student> sel();
}
public interface ClazzMapper {
  @Select("select * from t_class where id=#{0}")
  Clazz selById(int id);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值