• Mybatis从入门到CRUD到分页到日志到Lombok到动态SQL再到缓存


    Mybatis

    入门

    1.导入maven依赖

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>x.x.xversion>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.配置核心文件

    
    
    
        
            
                
                
                    
                    
                    
                    
                
            
        
    
    
        
    
            
        
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3.从 XML 中构建 SqlSessionFactory

    编写mybatis工具类

    package com.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;
    import java.io.InputStream;
    
    /*SqlSessionFactory --> sqlSession */
    public class MybatisUtils{
        //提升作用域
        private static SqlSessionFactory sqlSessionFactory;
    
        static{
    
            try {
                String resource="mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public  static SqlSession getSqlSession(){
            return  sqlSessionFactory.openSession();
    
           /* SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;*/
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    dao接口

    public interface Userdao {
        List getUserList();
    }
    
    • 1
    • 2
    • 3

    接口实现类由原来的UserDaolmpl转变为-一个Mapper配置文件.

    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试

    public class UserdaoTest {
        @Test
        public  void  test(){
            //第一步获得SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //方式一getMapper
          /*  Userdao userdao = sqlSession.getMapper(Userdao.class);
            List userList = userdao.getUserList();*/
    
            //方式二
            List userList = sqlSession.selectList("com.dao.Userdao.getUserList");
    
            for (User user : userList) {
                System.out.println(user);
            }
            sqlSession.close();
        }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    测试二

    public class UserdaoTest {
        @Test
        public  void  test(){
            //第一步获得SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            try{
                //方式一getMapper
                Userdao userdao = sqlSession.getMapper(Userdao.class);
                List userList = userdao.getUserList();
                for (User user : userList) {
                    System.out.println(user);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //关闭sqlSession
                sqlSession.close();
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    实现步骤

    在这里插入图片描述

    CRUD

    select

    insert

    update

    dalete

    创建实体类

    package com.pojo;
    
    public class User {
        private  int  id;
        private  String  name;
        private String pwd;
    
        public User() {
        }
    
        public User(int id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    编写接口

    public interface UserMapper {
        //查询所有用户
        List<User> getUserList();
        //根据id查询客户
         User getUserById(int id);
         //新增
         int addUser(User user);
         //修改
        int update(User user);
        //删除
        int dalete(int id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    编写对应sql语句

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     //查询所有用户
    <mapper namespace="com.dao.UserMapper">
    <select id="getUserList" resultType="com.pojo.User">
        select *from user
    select>
        //根据id查询客户
        <select id="getUserById" parameterType="int" resultType="com.pojo.User">
            select *from user where  id = #{id};
        select>
     //新增
        <insert id="addUser" parameterType="com.pojo.User">
            insert  into user (id,name,pwd) values (#{id},#{name},#{pwd})
        insert>
      //修改
        <update id="update" parameterType="com.pojo.User">
            update user
            set  name =#{name},pwd = #{pwd} where id = #{id};
        update>
         //删除
        <delete id="dalete" parameterType="int">
            delete  from user where  id = #{id};
        delete>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    测试

    public class UserdaoTest {
        @Test
        public  void  test(){
            //第一步获得SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            try{
                //方式一getMapper
                UserMapper mapper= sqlSession.getMapper(UserMapper.class);
                List<User> userList = mapper.getUserList();
                for (User user : userList) {
                    System.out.println(user);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //关闭sqlSession
                sqlSession.close();
            }
    
    
            //方式二
           /* List userList = sqlSession.selectList("com.dao.Userdao.getUserList");*/
    
    
        }
    
        @Test
        public  void getUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User userById = mapper.getUserById(1);
            System.out.println(userById);
            sqlSession.close();
        }
        @Test
        public  void addUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
             int res= mapper.addUser(new User(4,"王瑞","123"));
             if (res>0){
                 System.out.println("添加成功");
             }
    
             sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public  void update(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int update = mapper.update(new User(4, "徐龙象", "1999"));
            /*if(update>0){v
                System.out.println("修改成功");
            }*/
            sqlSession.commit();
            sqlSession.close();
        }
        @Test
        public  void dalete(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
           mapper.dalete(4);
            sqlSession.commit();
            sqlSession.close();
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    万能map

    Map传递参数,直接在sq|中取出key即可! [parameterType=“map”]
    对象传递参数,直接在sq|中取对象的属性即可! [parameterType=“Object”]
    只有一个基本类型参数的情况下,可以直接在sq|中取到!
    多个参数用Map,或者注解!

    新增
    接口
     //map
    int addUser2(Mapmap);
    
    • 1
    • 2
    sql连接
    
        insert  into user (id,pwd) values (#{userid},#{password})
    
    
    • 1
    • 2
    • 3
    测试
    @Test
    public void  addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //HashMap
        Map map = new HashMap();
        map.put("userid",5);
        map.put("password","123");
      mapper.addUser2(map);
      sqlSession.commit();
        sqlSession.close();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    查询
    sql
    
    
    
    • 1
    • 2
    • 3
    • 4
    接口
    User getUserById2(Mapmap);
    
    • 1
    测试
    @Test
    public  void getUserById2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap map = new HashMap<>();
        map.put("id",1);
        mapper.getUserById2(map);
        System.out.println(mapper.getUserById2(map));
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Mybatis模糊查询

    Java代码执行的时候,传递通配符% %

    List userListLike = mapper.getUserListLike("%xu%");
    
    • 1

    2.在sq|拼接中使用通配符!

    接口
    List getUserListLike(String name);
    
    • 1
    sql

    根据name查询

    
    
    • 1
    • 2
    • 3
    测试
    @Test
    public  void getUserListLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List userListLike = mapper.getUserListLike("xu");
        for (User user : userListLike) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    配置解析

    1.核心配置文件

    mybaits-config.xml

    configuration(配置)
    
        properties(属性)
        settings(设置)
        typeAliases(类型别名)
        typeHandlers(类型处理器)
        objectFactory(对象工厂)
        plugins(插件)
        environments(环境配置)
            environment(环境变量)
                transactionManager(事务管理器)
                dataSource(数据源)
        databaseIdProvider(数据库厂商标识)
        mappers(映射器)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1.环境配置(environments)

    尽管可以配置多个环境,但每个 SqlSessionFactory(创建SqlSession的工厂)实例只能选择一种环境。

    Mybatis默认的事务管理器就是JDBC,
    连接池:POOLED

    
    <environments default="test">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    
    
        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2.properties(属性)

    新建db. properties文件
    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=123456
    
    • 1
    • 2
    • 3
    • 4
    mybatis-config.xml
    
    
        
            
            
                
                
                
                
            
        
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    或者

    
      
      
    
    
    • 1
    • 2
    • 3
    • 4

    可以直接引入外部文件
    可以在其中增加一-些属性配置
    如果两个文件有同一个字段,优先使用外部配置文件的!

    3.类型别名(typeAliases)

    类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写

    
    
        
    
    
    • 1
    • 2
    • 3
    • 4
    2.指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
    
        
    
    
    • 1
    • 2
    • 3

    每一个在包 com.pojo 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 com.pojo` 的别名为 userhello;若有注解,则别名为其注解值。

    @Alias("userhello")
    public class User {
    
    • 1
    • 2

    4.设置(settings)

    一个配置完整的 settings 元素的示例如下:

    <settings>
        //全局性地开启或关闭所有映射器配置文件中已配置的任何缓存
      <setting name="cacheEnabled" value="true"/>
        //延迟加载的全局开关
      <setting name="lazyLoadingEnabled" value="true"/>
        //是否允许单个语句返回多结果集
      <setting name="multipleResultSetsEnabled" value="true"/>
        //使用列标签代替列名,实际表现依赖于数据库驱动
      <setting name="useColumnLabel" value="true"/>
        //允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。
      <setting name="useGeneratedKeys" value="false"/>
        //指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集
      <setting name="autoMappingBehavior" value="PARTIAL"/>
        /*
        指定发现自动映射目标未知列(或未知属性类型)的行为。
        NONE: 不做任何反应
        WARNING: 输出警告日志( org.apache.ibatis.session.AutoMappingUnknownColumnBehavior 的日志等级必须设置为 WARN)
        FAILING: 映射失败 (抛出 SqlSessionException)
        */
      <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
        /*
        配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement), BATCH 执行器不仅重用语句还会执行批量更新。
        支持 SIMPLE REUSE BATCH
        默认 SIMPLE
        */
      <setting name="defaultExecutorType" value="SIMPLE"/>
        //设置超时时间,它决定数据库驱动等待数据库响应的秒数。
      <setting name="defaultStatementTimeout" value="25"/>
        //控制每次从数据库获取数据的行数
      <setting name="defaultFetchSize" value="100"/>
        //允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为false
      <setting name="safeRowBoundsEnabled" value="false"/>
        //是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射
      <setting name="mapUnderscoreToCamelCase" value="false"/>
        /*
        MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。
        */
      <setting name="localCacheScope" value="SESSION"/>
        /*
        当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。
        JdbcType常用值:NULL、VARCHAR 或 OTHER。
        默认 OTHER
        */
      <setting name="jdbcTypeForNull" value="OTHER"/>
       /* 
        指定对象的哪些方法触发一次延迟加载。
        支持 用逗号分隔的方法列表。
        默认 equals,clone,hashCode,toString
        */
      <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    5.其他设置

    typeHandlers (类型处理器)

    objectFactory (对象工厂)
    plugins插件
    mybatis-generator-core
    。mybatis-plus
    。通用mapper

    6.映射器(mappers)

    使用相对于类路径的资源引用
    
    
      
      
      
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    使用完全限定资源定位符(URL)
    
    
      
      
      
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    使用映射器接口实现类的完全限定类名
    
    
      
      
      
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    将包内的映射器接口实现全部注册为映射器
    
    
      
    
    
    • 1
    • 2
    • 3
    • 4

    生命周期和作用域

    在这里插入图片描述

    错误的使用会导致非常严重的并发问题。

    SqlSessionFactoryBuilder:

    创建了SqlSessionFactory, 就不再需要它了,管杀不管埋
    局部变量

    SqlSessionFactory:

    可以想象为:数据库连接池,SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建
    另一个实例。
    因此SqlSessionFactory的最佳作用域是应用作用域,最简单的就是使用单例模式或者静态单例模式。

    SqlSession

    连接到连接池的一个请求,SqISession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用
    域,用完之后需要赶紧关闭,否则资源被占用,赶紧埋

    在这里插入图片描述

    这里面的每一个Mapper, 就代表一个具体的业务

    解决属性名与字段名不一致的问题

    解决方法:起别名

     
    
    • 1
    • 2
    • 3
    • 4

    resultMap结果集映射

    <!--结果集映射-->
        <resultMap id="UserMap" type="User">
            <id property="id" column="id"></id>
            <result column="name" property="name"/>
            <result column="pwd" property="password"/>
        </resultMap>
    <select id="getUserList" resultMap="UserMap">
        select *from mybatis.user
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    resu1tmap元素是MyBatis中最重要最强大的元素
    ●ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂- -点的语句
    只需要描述它们的关系就行了。
    ●Resu1tmap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。
    ●如果世界总是这么简单就好了。

    日志

    日志工厂

    SLF4J

    LOG4J(deprecated since 3.5.9)

    LOG4J2

    JDK_LOGGING

    COMMONS_LOGGING

    STDOUT_LOGGING(重点掌握)

    NO_LOGGING

    在Mybatis中具体使用那个一日志实现,在设置中设定!

    STDOUT_ LOGGING标准日志输出

    mybatis核心配置文件中,配置日志

    mybatis-config.xml

    
        
    
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    LOG4J(deprecated since 3.5.9)

    Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程

    我们也可以控制每一条日志的输出格式;
    通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
    通过一个配置文件来灵活地进行配置,而不需要修改应 用的代码。

    ### 配置根 ###
    log4j.rootLogger = debug,console ,fileAppender,dailyRollingFile,ROLLING_FILE,MAIL,DATABASE
    
    ### 设置输出sql的级别,其中logger后面的内容全部为jar包中所包含的包名 ###
    log4j.logger.org.apache=dubug
    log4j.logger.java.sql.Connection=dubug
    log4j.logger.java.sql.Statement=dubug
    log4j.logger.java.sql.PreparedStatement=dubug
    log4j.logger.java.sql.ResultSet=dubug
    ### 配置输出到控制台 ###
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
    
    ### 配置输出到文件 ###
    log4j.appender.fileAppender = org.apache.log4j.FileAppender
    log4j.appender.fileAppender.File = logs/log.log
    log4j.appender.fileAppender.Append = true
    log4j.appender.fileAppender.Threshold = DEBUG
    log4j.appender.fileAppender.layout = org.apache.log4j.PatternLayout
    log4j.appender.fileAppender.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
    
    ### 配置输出到文件,并且每天都创建一个文件 ###
    log4j.appender.dailyRollingFile = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.dailyRollingFile.File = logs/log.log
    log4j.appender.dailyRollingFile.Append = true
    log4j.appender.dailyRollingFile.Threshold = DEBUG
    log4j.appender.dailyRollingFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.dailyRollingFile.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n### 配置输出到文件,且大小到达指定尺寸的时候产生一个新的文件 ###log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender log4j.appender.ROLLING_FILE.Threshold=ERROR log4j.appender.ROLLING_FILE.File=rolling.log log4j.appender.ROLLING_FILE.Append=true log4j.appender.ROLLING_FILE.MaxFileSize=10KB log4j.appender.ROLLING_FILE.MaxBackupIndex=1 log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
    
    ### 配置输出到邮件 ###
    log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
    log4j.appender.MAIL.Threshold=FATAL
    log4j.appender.MAIL.BufferSize=10
    log4j.appender.MAIL.From=chenyl@yeqiangwei.com
    log4j.appender.MAIL.SMTPHost=mail.hollycrm.com
    log4j.appender.MAIL.Subject=Log4J Message
    log4j.appender.MAIL.To=chenyl@yeqiangwei.com
    log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
    log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
    
    ### 配置输出到数据库 ###
    log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
    log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/mybatis
    log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
    log4j.appender.DATABASE.user=root
    log4j.appender.DATABASE.password=123456
    log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n')
    log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
    log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
    log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.A1.File=SampleMessages.log4j
    log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'
    log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    基础使用

    1.在要使用Log4j的类中,导入包import org.apache.log4j.Logger;
    2.日志对象,参数为当前类的class

    static Logger logger = Logger.getLogger(UserdaoTest.class);
    
    • 1
    日志级别

    常用

    logger.info("info:进入了testlgo4j");
    logger.debug("debug:进入");
    logger.error("error");
    
    • 1
    • 2
    • 3

    分页

    减少数据的处理量

    使用Limit分页
    SELECT  *from mybatis.user limit strindex pagesize
    SELECT  *from mybatis.user limit 3,1;
    
    • 1
    • 2
    使用Mybatis实现分页

    1.接口

    List getUserLimit(Map map);
    
    • 1

    2.mapper.xml

    
    
    • 1
    • 2
    • 3

    3.测试

    @Test
    public  void  getUserLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap hashMap = new HashMap<>();
        hashMap.put("startIndex" ,1);
        hashMap.put("pageSize",4);
    
        List userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    RowBounds分页

    接口
    List getUserByRowBounds();
    
    • 1
    mapper.xml
    
    
    
    • 1
    • 2
    • 3
    • 4
    测试
    @Test
    public  void getUserByRowBounds(){
        RowBounds rowBounds = new RowBounds(1,2);
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        List<User> selectList = sqlSession.selectList("com.dao.UserMapper.getUserByRowBounds",null,rowBounds);
        for (User user : selectList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    分页插件

    导入

    
    
        com.github.pagehelper
        pagehelper
        5.3.0
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    https://pagehelper.github.io/docs/howtouse/

    在这里插入图片描述

    使用注解开发

    注解在接口上实现

    @Select("select *from user")
    List<User> geUsers();
    
    • 1
    • 2

    在mybatis-config中绑定接口

    
    
      
    
    
    • 1
    • 2
    • 3
    • 4

    CRUD

    mapper.xml

    public interface UserMapper {
        @Select("select *from user")
        List<User> geUsers();
    
    //方法存在多个参数,所有的参数前面必须加上@Param("id")注解
        //查询
        @Select("select * from user where id =#{id}")
        User getUserByID(@Param("id") int id );
        //新增    
        @Insert(" insert  into mybatis.user (id,name,pwd) values (#{id},#{name},#{password})")
        int addUser(User user);
        //修改    
        @Update(" update user set  name =#{name},pwd = #{password} where id = #{id}")
        int update(User user); 
        //删除    
        @Delete("delete  from mybatis.user where  id = #{id};")
        int datele(@Param("id") int id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    基本类型的参数或者String类型,需要加上, 引用类型不需要加,如果只有一个基本类型的话,可以忽略,
    在SQL中引用的就是@Param()中设定的属性名!

    Lombok

    1.在IDEA中安装Lombok插件!
    2.在项目中导入lombok的jar包
    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.22version>
        <scope>providedscope>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    在实体类上添加注解
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
     private  int id;
     private String name;
        private String password;
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    多对一处理

    数据表

    CREATE TABLE teacher(
    
    id int(10) NOT NULL,
    name VARCHAR(30) DEFAULT NULL,
    PRIMARY	 KEY(id)
    )ENGINE=INNODB DEFAULT CHARSET=utf8
    
    INSERT into teacher(id,name) VALUES (1,'陈老师');
    
    CREATE TABLE student (
    id int(10) NOT NULL,
    name VARCHAR(30) DEFAULT NULL,
    tid INT(10) DEFAULT NULL,
    PRIMARY	 KEY(id),
    KEY fktid (tid),
    CONSTRAINT fktid FOREIGN KEY (tid) REFERENCES teacher (id)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8
    
    INSERT INTO student (id,name,tid) VALUES ('1','小白','1');
    INSERT INTO student (id,name,tid) VALUES ('2','小李','1');
    INSERT INTO student (id,name,tid) VALUES ('3','小明','1');
    INSERT INTO student (id,name,tid) VALUES ('4','小宋','1');
    INSERT INTO student (id,name,tid) VALUES ('5','小王','1');
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    测试步骤

    1.导入lombok
    2.新建实体类Teacher, Student
    3.建立Mapper接口
    4.建立Mapper .XML文件
    5.在核心配置文件中绑定注册我们的Mapper接口或者文件.
    6.测试查询是否能够成功

    按照查询嵌套处理

    思路:
    1.查询所有的学生信息
    2.根据查询出来的学生的tid,寻找对应的老师

    
    select>
        <resultMap id="StudentTeacher" type="com.pojo.Student">
            <result property="id" column="id"/>
            <result property="name" column="name"/>
            
            <association property="teacher" column="tid" javaType="com.pojo.Teacher"  select="getTeacher"/>
        resultMap>
                 
        
        <select id="getTeacher" resultType="com.pojo.Teacher">
            select * from mybatis.teacher where id = #{uid}
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    按照结果集查询

        <select id="getStudent2"  resultMap="StudentTeacher2">
            select s.id sid, s.name,t.name tname
    from mybatis.student s ,mybatis.teacher t
    where s.tid = t.id
        select>
        <resultMap id="StudentTeacher2" type="com.pojo.Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <association property="teacher" javaType="com.pojo.Teacher">
                <result property="name" column="tname"/>
            association>
        resultMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    一对多处理

    实体类

    老师

    @Data
    public class Teacher {
        private  int id;
        private  String  name;
        private List students;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    学生

    @Data
    public class Student {
        private  int id;
        private String name;
        private int tid;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    按照结果集查询处理

       <select id="getTeacher" resultMap="TeacherStudent">
            select  s.id sid,s.name sname,t.name tname ,t.id tid
            from mybatis.student s ,mybatis.teacher t
            where s.tid = t.id and t.id = #{tid}
        select>
    
        <resultMap id="TeacherStudent" type="com.pojo.Teacher">
            <result property="id" column="tid"/>
            <result property="name" column="tname"/>
            
            <collection property="students" ofType="com.pojo.Student">
                <result property="id" column="sid"/>
                <result property="name" column="sname"/>
                <result property="tid" column="tid"/>
            collection>
        resultMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    按照查询嵌套处理

    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from mybatis.teacher where id = #{tid}
    select>
    <resultMap id="TeacherStudent2" type="com.pojo.Teacher">
        <collection property="students"  javaType="ArrayList" ofType="com.pojo.Student" select="getStudentByTeacherId" column="id"/>
    resultMap>
    <select id="getStudentByTeacherId" resultType="com.pojo.Student">
        select  * from mybatis.student where tid = #{tid}
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    小结

    1.关联-association [多对一 ]
    2.集合-collection [- 对多 ]

    1. javaType & ofType
    2. JavaType用来指定实体类中属性的类型
    3. ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

    动态 SQL

    动态SQL:根据不同的条件生成不同的SQL语句

    在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类。

    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach

    数据表

    CREATE TABLE `blog`(
    `id` VARCHAR(50) NOT NULL COMMENT '博客id',
    `title` VARCHAR(100) NOT NULL COMMENT '博客标题',
    `author` VARCHAR(30) NOT NULL COMMENT '博客作者',
    `create_time` DATETIME NOT NULL COMMENT '创建时间',
    `views` INT(30) NOT NULL COMMENT '浏览量'
    )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    编写实体类

    private int id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @SuppressWarnings("all")//抑制警告
    
    • 1

    mapper.xml

    <insert id="addBlog" parameterType="com.pojo.Blog">
        insert into mybatis.blog(id, title, author, create_time, views)
        values (#{id}, #{title}, #{author}, #{create_time}, #{views})
    
    insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试插入

    @Test
    public  void addInitBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("陈平安");
        blog.setCreate_time(new Date());
        blog.setViews(9999);
    
        mapper.addBlog(blog);
    
        blog.setId(IDUtils.getId());
        blog.setTitle("spring");
        mapper.addBlog(blog);
    
        blog.setId(IDUtils.getId());
        blog.setTitle("SpringMVC");
        mapper.addBlog(blog);
    
        blog.setId(IDUtils.getId());
        blog.setTitle("");
        mapper.addBlog(blog);
        sqlSession.commit();
        sqlSession.close();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    if语句

    接口
    List<Blog> queryBlogIF(Map map);
    
    • 1
    查询语句
        <select id="queryBlogIF" parameterType="map" resultType="com.pojo.Blog">
            select  * from  mybatis.blog where 1=1
    <if test="title != null">
       and title = #{title}
    if>
    <if test="author !=null">
        and author = #{author}
    if>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    测试
      @Test
    public  void queryBlogIF(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            HashMap hashMap = new HashMap();
            //hashMap.put("title","Java");
            hashMap.put("author","陈平安");
            List<Blog> blogs = mapper.queryBlogIF(hashMap);
            for (Blog blog : blogs) {
                System.out.println(blog);
            }
            sqlSession.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    choose、when、otherwise

    有时,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

    策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 views 的 BLOG

        <select id="queryBlogChoose" parameterType="map" resultType="com.pojo.Blog">
            select * from  mybatis.blog
            <where>
              <choose>
                  
                  <when test="title!=null">
                      title = #{title}
                  when>
                  
                 <when test="author != null">
                        and author = #{author}
                 when>
    <otherwise>
         
        and views = #{views}
    otherwise>
              choose>
            where>
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    trim、where、set

    where

    where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

     <select id="queryBlogIF" parameterType="map" resultType="com.pojo.Blog">
            select  * from  mybatis.blog
            <where>
    <if test="title != null">
       title = #{title}
    if>
    <if test="author !=null">
        and author = #{author}
    if>
            where>
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    set
    
        update mybatis.blog
    
      
          title = #{title}
      
    
    author = #{author}
    
    
    where id = #{id}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面, 去执行一个逻辑代码

    SQL片段

    1.使用SQL标签抽取公共的部分
     
        <sql id="addBlog">
            insert into mybatis.blog(id, title, author, create_time, views)
            values (#{id}, #{title}, #{author}, #{create_time}, #{views})
        sql>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2.在需要使用的地方使用Include标签引用即可
     <insert id="addBlog" parameterType="com.pojo.Blog">
       <include refid="addBlog">include>
    
    • 1
    • 2

    foreach

    在这里插入图片描述

    <select id="queryBlogForeach" parameterType="map" resultType="com.pojo.Blog">
            select  * from  mybatis.blog
    <where>
        <foreach collection="ibs" item="id" open="and (" close=")" separator="or">
    
    id = #{id}
        foreach>
    where>
        select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    测试
    @Test
        public  void queryBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList ibs = new ArrayList<>();
        ibs.add(1);
        ibs.add(2);
        ibs.add(3);
        map.put("ibs",ibs);
        List blogs = mapper.queryBlogForeach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    
        sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    动态SQL就是在拼接SQL语句,我们只需保证SQL的正确性,按照SQL的格式,去排列组合就可以了。先在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!

    缓存

    读写分离,主从赋值 数据库注意点

    1.简介

    1.什么是缓存[ Cache ]
    存在内存中的临时数据。
    将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查
    询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
    2.为什么使用缓存?
    减少和数据库的交互次数,减少系统开销,提高系统效率。
    3.什么样的数据能使用缓存?
    经常查询并且不经常改变的数据。 [可以使用缓存]

    2.Mybatis缓存

    MyBatis包含一 个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率

    MyBatis系统中默认定义了两级缓存: 一级缓存和二级缓存

    默认情况下,只有一级缓存开启。(SqISession级别的缓存, 也称为本地缓存)

    二级缓存需要手动开启和配置,他是基于namespace级别的缓存。

    为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

    一级缓存

    一级缓存也叫本地缓存:
    与数据库同一次会话期间查询到的数据会放在本地缓存中。
    以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

      SqlSession sqlSession = MybatisUtils.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
     User user =  mapper.queryUserIdBy(1);
      System.out.println(user);
    
      System.out.println("+++++++++++++++++++=");
    User user1 = mapper.queryUserIdBy(1);
      System.out.println(user1);
    
    
      System.out.println(user == user1);
      sqlSession.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    缓存失效的情况:
    在这里插入图片描述

    1.查询不同的数据
    2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存

      SqlSession sqlSession = MybatisUtils.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
     User user =  mapper.queryUserIdBy(1);
      System.out.println(user);
    
      mapper.update(new User(2,"aaa","bbb"));
      System.out.println("+++++++++++++++++++=");
    User user1 = mapper.queryUserIdBy(1);
      System.out.println(user1);
    
    
      System.out.println(user == user1);
      sqlSession.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3.查询不同的Mapper.xml在这里插入图片描述

    4.手动清理缓存!
    在这里插入图片描述
    在这里插入图片描述

    一级缓存默认是开启的,只在一次SqISession中有效, 也就是拿到连接到关闭连接这个区间段!

    二级缓存
    设置
    cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue

    默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存,要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

    UserMapper.xml中
    
    
    • 1
    • 2

    二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
    基于namespace级别的缓存,-一个名称空间,对应一个二级缓存;

    工作机制
    一个会话查询一条数据,这个数据就会被放在当前会话的- -级缓存中;
    如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,- -级缓存中的
    数据被保存到二级缓存中;
    新的会话查询信息,就可以从二级缓存中获取内容;
    不同的mapper查出的数据会放在自己对应的缓存(map) 中;

    步骤一

    1.开启全局缓存

    
    
    • 1

    2.在要使用二级缓存的Mapper中开启

    
    
    • 1

    也可以自定义属性

    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.测试

    需要将实体类进行序列化,否则报错

    Caused by: java. io. NotSerializableException: com. kuang. pojo. User
    
    • 1

    小结

    只要开启了二级缓存,在同一个Mapper下就有效
    所有的数据都会先放在一级缓存中;
    只有当会话提交,或者关闭的时候,才会提交到二级缓存中

    缓存原理

    在这里插入图片描述

    自定义缓存

    1.导入maven依赖

    
    
        org.mybatis.caches
        mybatis-ehcache
        1.2.2
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.在mapper.xml中配置

    
    
    
    • 1
    • 2

    2.创建配置文件

    Ehcache.xml

    
    
    
        
    
        
    
        
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    以下属性是必须的:

    **name:**Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。

    **maxElementsInMemory:**在内存中缓存的element的最大数目。

    **maxElementsOnDisk:**在磁盘上缓存的element的最大数目,默认值为0,表示不限制。

    **eternal:**设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断。

    **overflowToDisk:**如果内存中数据超过内存限制,是否要缓存到磁盘上。

    以下属性是可选的:

    **timeToIdleSeconds:**对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。

    **timeToLiveSeconds:**对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。

    **diskPersistent:**是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。

    **diskExpiryThreadIntervalSeconds:**对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。

    **diskSpoolBufferSizeMB:**DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。

    memoryStoreEvictionPolicy:如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。

    缓存的3 种清空策略

    FIFO,first in first out (先进先出).

    LFU, Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。

    LRU,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

    结束啦

         updateCheck="false">
    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    ```

    以下属性是必须的:

    **name:**Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。

    **maxElementsInMemory:**在内存中缓存的element的最大数目。

    **maxElementsOnDisk:**在磁盘上缓存的element的最大数目,默认值为0,表示不限制。

    **eternal:**设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断。

    **overflowToDisk:**如果内存中数据超过内存限制,是否要缓存到磁盘上。

    以下属性是可选的:

    **timeToIdleSeconds:**对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。

    **timeToLiveSeconds:**对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。

    **diskPersistent:**是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。

    **diskExpiryThreadIntervalSeconds:**对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。

    **diskSpoolBufferSizeMB:**DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。

    memoryStoreEvictionPolicy:如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。

    缓存的3 种清空策略

    FIFO,first in first out (先进先出).

    LFU, Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。

    LRU,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

    结束啦

  • 相关阅读:
    解决javax.mail.MessagingException: Could not convert socket to TLS;
    【云存储】Go项目实践(Fedora、GlusterFS、ownCloud)
    【华为OD机试python】模拟消息队列【2023 B卷|100分】
    大部分PHP程序员,都搞不懂如何安全代码部署【二】(nginx篇)
    自己动手实现rpc框架(二) 实现集群间rpc通信
    基于FTP协议的Excel文件上传与下载
    基于Hardhat和Openzeppelin开发可升级合约(二)
    DevZone
    vue vue 常用的扩展组件
    深度学习(四)之电影评论分类
  • 原文地址:https://blog.csdn.net/weixin_51627264/article/details/136530242