Mybatis-9.28

Mybatis-9.28

环境:

  • JDK1.8
  • Mysql 5.7
  • maven 3.6.1
  • IDEA

回顾:

  • JDBC
  • Mysql
  • Java基础
  • Maven
  • Junit

SSM框架:配置文件的最好的学习方式:看官网文档;

1、简介

1.1、什么是Mybatis

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
  • MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了[google code](https://baike.baidu.com/item/google code/2346604?fromModule=lemma_inlink),并且改名为MyBatis。2013年11月迁移到Github
  • iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)。

如何获取Mybatis

  1. github:Mybatis-3

  2. Maven:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.10</version>
    </dependency>
    
    
  3. 中文文档:Mybatis中文网

1.2、持久层

数据持久化

  • 持久化:就是将程序的数据在持久状态瞬时状态转化的过程
  • 内存:断电即失
  • 数据库(jdbc):io文件持久化。
  • 生活:冷藏、罐头。

为什么需要持久化?

有一些对象,不能让他丢掉。

  • 内存太贵了

1.3、持久层

Dao层、Service层、Controller层……

  • 完成持久化工作的代码块
  • 层界限十分明显

1.4、为什么需要Mybatis、

  • 方便
  • 传统的JDBC代码太复杂。简化、框架。
  • 帮助程序猿将数据存入到数据库中
  • 不用Mybatis也可以。更容易上手。技术没有高低之分,只有使用这个技术的人有高低之别
  • 优点:
    • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
    • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
    • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
    • 提供映射标签,支持对象与数据库的ORM字段关系映射。
    • 提供对象关系映射标签,支持对象关系组建维护。
    • 提供xml标签,支持编写动态sql。 [2]

最重要的一点:使用的人多!

2、第一个Mybatis程序

思路 :搭建环境–>导入mybatis–>编写代码–>测试!

2.1、搭建环境

搭建数据库

CREATE TABLE [IF  EXISTS] `user`(
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`pwd`	VARCHAR(18) 	DEFAULT NULL,
PRIMARY KEY(`ID`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES 
(1,'XQY','123456'),
(2,'WXZ','123456'),
(3,'SJX','123456')

新建项目

1.新建一个普通maven项目

2.删除src

3.导入maven依赖

<!--导入依赖-->
        <dependencies>
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.46</version>
            </dependency>
            <!--mybatis驱动-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <!--junit驱动-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
        </dependencies>

2.2、创建一个模块

  • 编写mybatis核心配置文件

    <?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 核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <!--事物管理-->
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value=".com.mysql.jdbc.Driver"/>
                    <property name="url"
                            value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
  • 编写mybatis工具类

    package com.NanCheng.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 {
                //使用mybatis第一步获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    //    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    //    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        public static SqlSession/*相当于connection对象*/  getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

2.3、编写代码

  • DAO接口

    package com.NanCheng.dao;
    
    import com.NanCheng.pojo.User;
    
    import java.util.List;
    
    public interface UserDao {
        List<User> getUserList();
    }
    
    
  • 接口实现类由原来的impl转换为Mapper配置文件

    <?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">
    <!--namespace = 绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.NanCheng.dao.UserDao">
        <!--select查询语句-->
        <select id = "getUserList" resultType="com.NanCheng.pojo.User">
            select * form mybatis.user 
        </select>
    </mapper>
    

2.4、测试

注意点:org.apache.ibatis.binding.BindingException: Type interface com.NanCheng.mapper.UserMapper is not known to the MapperRegistry.

  • junit测试:

    package com.NanCheng.mapper;
    
    import com.NanCheng.pojo.User;
    import com.NanCheng.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    public class UserMapperTest {
        @Test
        public void test(){
            //第一步:获得sqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //第二步:执行SQL
    
            //方式一:getMapper
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
    
            //方式二:不推荐
    //        List<User> userList = sqlSession.selectList("com.NanCheng.mapper.UserMapper.getUserList");
    
    
            for (User user : userList) {
                System.out.println(user);
            }
    
            //关闭sqlSession
            sqlSession.close();
            //绑定错误!!!
    //        org.apache.ibatis.binding.BindingException:
    //        Type interface com.NanCheng.mapper.UserMapper is not known to the MapperRegistry.
    
    
    
        }
    }
    
    
  • 遇到的问题:

    问题1:
    上述过程中,在mybatis-config.xml文件中需要加上所有mapper类的注册语句。例如UserMapper:

    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--configuration 核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <!--事物管理-->
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url"
                            value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        
    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
        <mappers>
            <mapper resource="com/NanCheng/mapper/UserMapper.xml"/>
        </mappers>
    </configuration>
    

    问题2:
    由于我们的Mapper实现类是通过xml配置文件实现的,无法从java报中导出,所以需要在pom文件中加入过滤器

    <build>
        <!--java目录下.xml文件无法导出的解决方法-->
            <resources>
                <resource>
                    <directory>src/main/resource</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            </resources>
        </build>
    

    总结:

    1. 配置文件没有注册
    2. 绑定接口错误
    3. 方法名不对
    4. 返回类型不对
    5. Maven导出资源问题
    • 步骤:
      1. 配置pom.xml文件,导入mybatis、mysql、junit以及过滤器
      2. 编写MybatisUtils工具类,通过SqlSessionFactoryBuilder读取xml文件来返回一个SqlSessionFactory工厂,再通过工厂的openSession()方法返回SqlSession对象
      3. 编写mybatis-config.xml文件来连接数据库,执行jdbc所需要执行的事务管理。
      4. 创建实体类,与数据库表相对应。
      5. 创建Mapper接口。
      6. 创建Mapper.xml配置文件,在配置文件中使用mapper标签中的namespace[命名空间]来绑定一个对应的Dao/Mapper接口,再在其内部使用对应的标签来执行Sql语句。例如select标签,其中id对应需要执行的方法名resultType对应返回值的类型,此处resultType中应是返回值的绝对路径
      7. 编写测试类,建议测试包中关系层次与java包中对应。测试类中分三步:
        1. 获得SqlSession对象:通过MybatisUtils工具类中的getSqlSession()方法来获取。
        2. 执行Sql语句,获取结果集:一般通过使用SqlSession中的getMapper(e.class)方法来获取存储的结果集mapper,然后通过mapper中的方法将最终的结果转入List集合中打印。
        3. 最后关闭SqlSession。

3.CRUD

1、namespace

namespace中的包名要和Dao/Mapper接口的包名一致。

2、select

选择,查询语句:

  • id: 就是对应的namespace中的方法名
  • resultType:Sql语句执行的返回值。
  • parameterType:参数类型。
  1. 编写接口

    //根据id查询用户
    User getUserById(int id);
    
  2. 编写对应的mapper中的sql语句

    <!--查询具体id对应的User-->
        <select id = "getUserById" resultType="com.NanCheng.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
    
  3. 测试

    @Test
    public void testGetUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();//获得session对象
    
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);//获取UserMapper接口
    
        User user = mapper.getUserById(2);//执行接口内方法
    
        System.out.println(user);
        sqlSession.close();
    }
    

3、Insert

  1. 编写接口

    //插入用户
        int insertUser(User user);
    
  2. 编写对应mapper中的sql语句

    <!--User中的属性可以直接拿出来用-->
        <insert id = "insertUser"  parameterType="com.NanCheng.pojo.User" >
        insert into mybatis.user (`id`,`name`,`pwd`) values (#{id},#{name},#{pwd})
        </insert>
    
  3. 测试

    @Test
    public void testInsertUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();//工厂生产sqlSession
    
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);//获取接口
    
        User user = new User(04,"NanCheng","123456");
    
        mapper.insertUser(user);
        sqlSession.commit();//提交
        sqlSession.close();
    }
    

4、Update

  1. 编写接口

    //更新用户
    int updateUser(User user);
    
  2. 编写对应mapper中的sql语句

    <update id = "updateUser" parameterType="com.NanCheng.pojo.User">
        update user
        set name = #{name}
        where id = #{id};
    </update>
    
  3. 测试

    @Test
    public void testUpdateUser(){
        User user = new User(3, "呵呵", "123456");
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        mapper.updateUser(user);
        sqlSession.commit();
        sqlSession.close();
    }
    

5、Delete

  1. 编写接口

    //删除用户
    int deleteUser(User user);
    
  2. 编写对应mapper中的sql语句

    <!--删除方法-->
    <delete id = "deleteUser" parameterType="com.NanCheng.pojo.User">
        delete
        from user
        where id = #{id};
    </delete>
    
  3. 测试

    @Test
    public void testDeleteUser(){
        User user = new User(2);
        //工厂模式生成SqlSession -->mapper
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行Sql语句
        mapper.deleteUser(user);
        //提交
        sqlSession.commit();
        //关闭
        sqlSession.close();
    }
    
  • 注意:
    !!!增删改需要提交事物后数据库内容才会改变!!!
    所有的SqlSession对象使用完之后要记得关闭

6、错误分析

  1. namespace中包名用==’ . '==分割而不是其他。
  2. insert语句写在了selecr标签内
  3. mybatis-confi.xml文件中的mapper注册,里面的resource属性中,文件的绝对地址中包名的分割使用的是 ’ / ’
  4. 输出的xml文件中存在中文乱码的问题
  5. maven资源没有导出的问题

7、万能Map

假设,我们的实体类,或者数据库中的表,字段参数过多,我们就应当考虑使用Map!

接口:

//万能的map
    User addUser(Map<String,Object> map);

测试:

@Test
    public void testAddUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        //传入键值
        map.put("userid",5);
        map.put("userName","hello");
        map.put("passWord","222333");
        mapper.addUser(map);
        sqlSession.commit();
        sqlSession.close();
    }

xml配置:

<!--传递map的key-->
    <insert id="addUser" parameterType="map">
        insert into mybatis.user (id, name, pwd)  values (#{userid},#{userName},#{passWord})
    </insert>

Map传递参数,直接在sql中取出Key即可! parameterType=“map”

对象传递参数,直接在sql中取出对象即可! parameterType=“com.NanCheng.pojo.User”

只有一个基本类型参数的情况下,可以直接在sql中取到! parameterType=“int”

多个参数用Map 或者注解

8、模糊查询

模糊查询怎么写?

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

    System.out.println(Arrays.toString(mapper.getUserLike("%"+value+"%").toArray()));
    
  2. 在sql拼接中使用通配符!

    select * from mybatis.user where  name like  "%"#{value}"%"
    

4、配置解析

1、核心配置文件

  • mybatis-config.xml

  • Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息。

    configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    environment(环境变量)
    transactionManager(事务管理器)
    dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
    

2、环境配置(Environments)

MyBatis 可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

修改环境只需要修改defaut对应的环境就行

学会配置多套运行环境

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

3、属性(properties)

我们可以通过properties属性来实现引用配置文件。

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】

编写一个配置文件:

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

在核心配置文件中引入配置文件
在这里插入图片描述

<!--引入外部配置文件-->
<!--在使用的优先级上,如果外部配置文件和内部定义的property标签产生冲突,就会有限使用外部文件定义的属性-->
<properties resource="db.properties">
    <property name="username" value="root"/>
    <property name = "password" value = "123456" />
</properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果外部文件属性和内部属性冲突,优先使用外部文件属性

4、类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。

  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

<!--可以给实体类起别名-->
<typeAliases>
    <typeAlias type = "com.NanCheng.pojo.User" alias="User"/>
</typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

扫描实体类的包,它的默认别名就为这个类的别名,首字母小写!

<typeAliases>
	<pakage name = "com.NnaCheng.pojo"/>
</typeAliases>

在实体类使用较少的时候,使用第一张方式

如果实体类十分多,建议使用第二中。

第一种可以DIY,第二种不行,如果非要改,需要在实体类上增加@Alias("OtherName")注解来取别名。

@Alias("user")
public class User{ }

Java一些基本的数据类型或者常用类会有自己的别名,无需定义,详情如下:

别名映射的类型
_bytebyte
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal
objectObject
mapMap
hashmapHashMap
listList
arraylistArrayList
collectionCollection
iteratorIterator

5、设置(settings)

在这里插入图片描述

在这里插入图片描述

6、其他配置

7、映射器(mappers)

MapperReistry:注册绑定我们的Mapper文件;

方式一:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
        <mapper resource="com/NanCheng/mapper/UserMapper.xml"/>
    </mappers>

方式二:使用class文件取绑定注册

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
    <mapper class = "com.NanCheng.mapper.UserMapper"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的配置文件必须在同一个包下

方式三:使用扫描包进行注入绑定

<!-- 使用扫描包注入绑定 -->
<mappers>
    <package name = "com.NanCheng.mapper" />
</mappers>

注意点与方式二相同

8、生命周期和作用域

作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 一旦创建了SqlSessionFactoryBuilder,就不再需要它了
  • 局部变量

SqlSessionFactory:

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

SqlSession

  • 连接到连接池的一个请求。
  • SqlSession的实例不是线程安全的,因此是不能被共享的,每个线程都应该拥有它自己的SqlSession实例,所以它的最佳作用域是请求或者方法作用域。
  • 用完之后需要赶紧关闭,否则资源被占用!

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

5、解决属性名和字段名不一致的问题

数据库中的字段名:

实体类中的属性名

在这里插入图片描述

  • 起别名

    <select id = "getUserById" resultType="User">
    select id,name,pwd as password from mybatis.user where id = #{id}
    </select>
    

2、resultMap

结果集映射

id name pwd
id name password
<!--结果集-->
<resultMap id = "UserMap" type = "User">
    <!--col v  umn:数据库中的字段 property:类中的属性-->
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

6、日志

6.1、日志工厂

如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手。

曾经:sout,debug

现在:日志工厂!

在这里插入图片描述

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

在mybatis中具体使用哪一个日志实现,在设置中设定。

STDOUT_LOGGING 标准日志输出

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

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

在这里插入图片描述

6.2、Log4J

什么是Log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件。
  • 我们也可以控制每一条日志的输出格式。
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
  1. 如何导入log4j

    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>
    
  2. log4j.properties

    #日志文件输出的等级
    log4j.rootLogger=DEBUG,console,file
    
    #控制台输出的相关设置
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target=System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    
    #文件输出的相关设置
    log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=./log/NanCheng.log
    log4j.appender.file.MaxFileSize=10mb
    log4j.appender.file.Threshold=DEBUG
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
    
    #日志输出级别
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.ResultSet=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    
    
  3. 配置lo4j为日志的实现

    <settings>
        <setting name = "logImpl" value = "LOG4J" />
    </settings>
    
  4. Log4j的使用:直接测试运行

在这里插入图片描述

简单使用:

  1. 在要使用Log4j的类中,导入Log4j的包

  2. 日志对象,参数为当前类的class

    static Logger logger = Logger.getLogger(TestUserMapper.class);
    
  3. 日志级别:

    public  void testLog4J(){
        logger.info("info:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");
    }
    

7、分页

思考:为什么要分页

  • 减少数据的处理量

7.1使用Limit分页

语法: select * from user limit startIndex,pageSize

  • startIndex:从第几个人开始查

  • pageSize:每页的人数。

  • 如果只有一个参数,那么就是[0,n]

使用Mybatis实现分页,核心SQL

  1. 接口

    //分页
    List<User>  getUserLimit(Map<String,Integer> map);
    
  2. Mapper.xml

    <!--分页 查询-->
    <select id = "getUserLimit" resultMap="UserMap" parameterType="map">
        select * from mybatis.user limit #{startNum},#{endNum}
    </select>
    
  3. 测试

    @Test
    public void testGetUserLimit(){
        Map<String,Integer> map = new HashMap<String, Integer>();
        map.put("startNum",0);
        map.put("endNum",4);
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> limit = mapper.getUserLimit(map);
        for (User user : limit) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

7.2使用RowBounds分页

不再使用SQL实现分页

  1. 接口

    //RowBounds分页
    List<User> getUserByRowBounds();
    
  2. Mapper

    <!--分页2-->
    <select id = "getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
    
  3. 测试

    //分页2
    @Test
    public void testGetUserRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1,2);
        //通过java代码层面实现分页
        List<User> list = sqlSession.selectList("com.NanCheng.mapper.UserMapper.getUserByRowBounds",null,rowBounds);
        for (User user : list) {
            System.out.println(list);
        }
        sqlSession.close();
    }
    

7.3、分页插件

在这里插入图片描述

了解即可

8、使用注解开发

8.1、面向接口编程

虽然学习过面向对象编程,也学习过接口,但是在真正的开发中,很多时候我们都会选择面向接口编程

根本原因:解耦,可拓展,提高复用,分层开发中,上层不用关具体的实现,大家都遵守沟通的标准,使得开发变得容易,规范性更好。

  • 在一个面对对象的系统中,系统的各种功能是由许多不同的对象写作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了。
  • 而各个对象之间的协作关系则称为了系统设计的关键。笑道不同类之间的通信,大到各模块之间交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范、约束)与实现(名实分离原则)的分离。

  • 接口的本身反映了系统设计人员对系统的抽象理解。

  • 接口应有两类:

    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class)

      第二类接口是对一个个体某一方面的抽象,即形成一个抽象面(interface)

  • 一个个体有可能由多个抽象面,抽象提和抽象面是有区别的。

三个面向区别

  • 面向对象是指,我们考虑问题是,以对象为单位,考虑它的属性及方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象 过程)不是一个问题。更多的体现就是对系统整体的架构。

8.2、使用注解开发

  1. 注解在接口上实现

    @Select("select * from mybatis.user")
    List<User> getUsers();
    
  2. 需要在中心配置文件绑定接口

<!--绑定接口-->
<mappers>
    <mapper class="com.NanCheng.mapper.UserMapper"/>
</mappers>
  1. 测试

    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //底层主要应用了反射
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.getUsers();
        for (User user : list) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

本质:反射机制实现

底层:动态代理!

Mybatis详细执行流程!
在这里插入图片描述

8.3、CRUD

我们可以在工具类创建的时候实现自动提交事务!

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);//创建session
}

核心文件绑定接口

<!--绑定接口-->
<mappers>
    <mapper class="com.NanCheng.mapper.UserMapper"/>
</mappers>

编写接口,增加注解

package com.NanCheng.mapper;


import com.NanCheng.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
    //通过注解查询
    @Select("select * from mybatis.user")
    List<User> getUsers();

    //通过id查询    用@Param("param")可以将参数param传入sql语句当中
    // 如果方法存在多个参数,那么所有的参数都必须在其参数类型前使用@Param注解
    // 在Select中,其中参数id是取得@Param内对参数的定义名
    @Select("select * from mybatis.user where id = #{id}")
    User getUserById(@Param("id") int id);

    //插入
    @Insert("insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User user);

    //修改
    @Update("update user set name=#{NewName}, pwd=#{NewPwd} where id = #{id}")
    int updateUser(@Param("id") int id,@Param("NewName") String name,@Param("NewPwd") String pwd);
    
    //删除
    @Delete("delete from user where id = #{DelId}")
    int delUser(@Param("DelId") int id );
}

测试类

package com.NanCheng.mapper;


import com.NanCheng.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
    //通过注解查询
    @Select("select * from mybatis.user")
    List<User> getUsers();

    //通过id查询    用@Param("param")可以将参数param传入sql语句当中
    // 如果方法存在多个参数,那么所有的参数都必须在其参数类型前使用@Param注解
    // 在Select中,其中参数id是取得@Param内对参数的定义名
    @Select("select * from mybatis.user where id = #{id}")
    User getUserById(@Param("id") int id);

    //插入
    @Insert("insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User user);

    //修改
    @Update("update user set name=#{NewName}, pwd=#{NewPwd} where id = #{id}")
    int updateUser(@Param("id") int id,@Param("NewName") String name,@Param("NewPwd") String pwd);

    //删除
    @Delete("delete from user where id = #{DelId}")
    int delUser(@Param("DelId") int id );

}

关于@Param()注解

  • 基本类型的参数或者String类型需要加上,引用类型不加
  • 如果只有一个基本类型的话,可以忽略,但是建议都加上
  • 我们在SQL中引用的就是我们这里的@Param()中设置的属性名

#{} 、${}区别

${}会导致SQL的注入,破坏程序的健壮性,#{}不会。

9、Lombok

  1. 在 IDEA的插件中查询lombok,并且下载

  2. Maven仓库

    <dependencies>
    	<dependency>
    		<groupId>org.projectlombok</groupId>
    		<artifactId>lombok</artifactId>
    		<version>1.18.24</version>
    	</dependency>
    </dependencies>
    
  3. 在实体类上加注解即可

    package com.NanCheng.pojo;
    
    import lombok.*;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int id;
        private String name;
        private String password;
    }
    

注解类型

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass

说明:

@Data	//无参构造、get、set、toString、hashcode、equals
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString

10、多对一

在这里插入图片描述

  • 多个学生对应一个老师
  • 对于学生而言,关联…多个学生,关联一个老师【多对一】
  • 对于老师而言,集合,一个老师有很多学生【一对多】

SQL:

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,`NanCheng`);

create table `student` (
`id` int 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','s1','1');
insert into `student`(`id`,`name`,`id`) values ('2','s2','1');
insert into `student`(`id`,`name`,`id`) values ('3','s3','1');
insert into `student`(`id`,`name`,`id`) values ('4','s4','1');

测试环境搭建

  1. 导入Lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper配置文件
  5. 在核心配置文件中绑定注册我们的mapper接口或者文件【方式很多,随便写】
  6. 测试查询是否能够连接成功

按照查询嵌套处理

<!--思路:
    1.查询所有的学生信息
    2.根据查询出来的学生的tid,寻找对应的老师 子查询
    -->
    
    <select id = "getStudent" resultMap="StudentTeacher">
        select * from mybatis.student
    </select>
    <resultMap id = "StudentTeacher" type = "Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--
            复杂的属性,我们需要单独处理
            对象我们使用association:
                javaType是对象的类型
                select属性是复合调用的标签id
            集合我们使用collection
        -->
        <association property = "teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id = "getTeacher" resultType="Teacher">
        select * from mybatis.teacher where id = #{id}
    </select>

按照结果嵌套处理

<!--    通过结果嵌套查询-->
    <select id = "getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from teacher t ,student s
        where s.tid = t.id
    </select>
    
    <resultMap id = "StudentTeacher2" type = "Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property = "teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

回顾Mysql多对一查询方式:

  • 子查询

  • 联表查询

11、一对多

比如:一个老师拥有多个学生

对于老师而言,就是一对多的关系!

环境搭建:

实体类

package com.NanCheng.pojo;

import lombok.Data;
import org.apache.ibatis.type.Alias;

@Data
@Alias("Student")
public class Student {
    private int id;
    private String name;
    private int tid;
}
package com.NanCheng.pojo;


import lombok.Data;
import org.apache.ibatis.type.Alias;

import java.util.List;

@Data
@Alias("Teacher")
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}

按照结果查询处理

xml:

<!--结果嵌套查询-->
<resultMap id = "TeacherStudent" type = "Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--
    复杂的属性:我们需要单独处理 对象:association 集合:collection
    javaType = ""  指定的属性类型
    集合中的泛型信息,我们使用ofType获取
    -->
    
    <collection property = "students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
        
    </collection>
</resultMap>

<select id = "getTeacher" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname, t.id tid
    from student s,teacher t
    where s.tid=t.id and t.id = #{tid}
</select>

测试:

@Test
public void test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

    Teacher teacher = mapper.getTeacher(1);
    System.out.println(teacher);
    /**
     * Teacher(id=1, name=NanCheng, students=
     * [Student(id=1, name=s1, tid=1),
     * Student(id=2, name=s2, tid=1),
     * Student(id=3, name=s3, tid=1),
     * Student(id=4, name=s4, tid=1)])
     */

    sqlSession.close();
}

子查询处理

xml:

<select id = "getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id = "TeacherStudent2" type = "Teacher">
    <collection property = "students" javaType="ArrayList"
            ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id = "getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = #{tid}
</select>

测试:

@Test
public void test2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
    Teacher teacher2 = mapper.getTeacher2(1);

    System.out.println(teacher2);
    /**
     * Teacher(id=1, name=NanCheng, students=
     * [Student(id=1, name=s1, tid=1),
     * Student(id=2, name=s2, tid=1),
     * Student(id=3, name=s3, tid=1),
     * Student(id=4, name=s4, tid=1)])
     */

    sqlSession.close();
}

小结:

  1. 关联 - association【多对一】
  2. 集合 - collection【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的``pojo`类型,反省中的约束类型!

注意点

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志,建议使用log4j

慢SQL 1s 1000s

面试高频:

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化!

12、动态SQL

什么是动态SQL:动态SQL就是指根据不同的条件生产不同的SQL语句

动态SQL元素 和 JSTL或基于类似XML的文本处理器相似,在Mybatis之前的版本中,有很多元素需要花时间了解,Mybatis 3 大大精简了元素种类,现在只需学习原来一半的元素即可,Mybatis 采用功能强大的基于OGNL的表达式来满足其他大部分元素。

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

搭建环境

create table blog(
    `id` varchar(50) not null comment '博客 id',
    `title` varchar(50) not null comment'博客标题',
    `author` varchar(30) not null comment'博客作者',
    `creat_time` datetime not null comment'创建时间',
    `views` int(30) not null comment'浏览量' 
)engine=innodb default charset=utf8

IF

  1. 导入包

  2. 编写配置文件

    <!--开启自动转换大小写-->
    <setting name = "mapUnderscoreToCamelCase" value = "true" />
    
  3. 编写实体类

    package com.NanCheng.utils;
    
    
    import org.junit.Test;
    
    import java.util.UUID;
    
    @SuppressWarnings("all")//抑制警告
    public class IDutils {
        public static String getId(){
            return UUID.randomUUID().toString().replaceAll("-","");
        }
    
        @Test
        public void test(){
            System.out.println(IDutils.getId());
        }
    }
    
    package com.NanCheng.pojo;
    
    import lombok.Data;
    
    import java.util.Date;
    
    @Data
    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    }
    
  4. 编写实体类对应的mapper和mapper.xml文件

    package com.NanCheng.mapper;
    
    import com.NanCheng.pojo.Blog;
    
    import java.util.List;
    import java.util.Map;
    
    public interface BlogMapper {
        //添加博客方法
        int addBlog(Blog blog);
        //搜索方法
        List<Blog> getBlog(Map map);
    }
    
    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--namespace = 绑定一个对应的Dao/Mapper接口-->
    <mapper namespace = "com.NanCheng.mapper.BlogMapper">
        
        <insert id = "addBlog" parameterType="Blog">
            insert into mybatis.blog (id, title, author, create_time, views)
            values (#{id},#{title},#{author},#{createTime},#{views})
        </insert>
        
        
        
        <select id = "getBlog" parameterType="map" resultType="Blog">
            select * from blog where 1 = 1
            <if test = "title!=null">
                and title = #{title}
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
        </select> 
    
    </mapper>
    

Choose、when、ohterwise

接口:

package com.NanCheng.mapper;

import com.NanCheng.pojo.Blog;

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

public interface BlogMapper {
    //添加博客方法
    int addBlog(Blog blog);
    //if标签实现搜索方法
    List<Blog> getBlog(Map map);
    //choose、when、otherwise实现查询
    List<Blog> getBlogByChoose(Map map);
}

mapper:

<?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.NanCheng.mapper.BlogMapper">
    
    <insert id = "addBlog" parameterType="Blog">
        insert into mybatis.blog (id, title, author, create_time, views)
        values (#{id},#{title},#{author},#{createTime},#{views})
    </insert>
    
    
    
    <select id = "getBlog" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <if test = "title!=null">
               and title = #{title}
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
        </where>
    </select>
    <!--
        where标签会自动检测SQL语句,根据情况来判断是否需要加and
        choose/when/otherwise语句体系相对应java中的switch/case/default体系
    -->
    <select id = "getBlogByChoose" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <choose>
                <when test = "author!=null">
                     and author = #{author}
                </when>
                <when test = "title!=null">
                    and title = #{title}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>

</mapper>

测试:

@Test
public void testChoose(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();

    map.put("title","Java");
    map.put("author","NanCheng");

    List<Blog> blogByChoose = mapper.getBlogByChoose(map);

    for (Blog blog : blogByChoose) {
        System.out.println(blog);
    }

    sqlSession.close();
}

trim

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

if

where、set、choose、when

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

  1. 使用SQL标签抽取公共的部分

    <sql id="if-title-author">
        <if test="title!=null">
            title=#{title}
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </sql>
    
  2. 在需要使用的的地方使用include标签即可“

    <select id = "getBlog" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <include refid = "if-title-author"></include>
        </where>
    </select>
    

注意事项:

  • 最好基于单表来定义SQL片段!
  • 不要存在where标签

Foreach

select * from user where 1 = 1 and (id = 1 or id =2 or id = 3)

<!--
 select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
 我们现在传递一个万能的map,这个map中可以存在一个集合!
 -->
 <select id = "queryBlogForeach" parameterType="map" resultType="Blog">
     select * from mybatis.blog
     <where>
         <foreach collection = "ids" item="id" open="and (" close=")" separator="or">
             id=#{id}
         </foreach>
     </where>
</select>

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就ok了

建议:

  • 先在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!

13、缓存(了解即可)

13.1、简介

查询:连接数据库,耗 资源!

一次查询的结果,给它暂存在一个可以直接渠道的地方!–>内存:缓存

我们再次查询相同的数据的时候,直接走缓存,就不用走数据库了

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

13.2、Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存。缓存可以极大的提升查询效率。
  • Mybatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
    • 为了提高扩展性,Mybatis定义了缓存接口Cache。我们可以通过Cache接口来自定义二级缓存。

13.3、一级缓存

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

测试步骤:

  1. 开启日志

  2. 测试在一个Session中查询两次相同记录

  3. 查看日志输出
    在这里插入图片描述

    缓存失效的情况:

    1. 查询不同的东西

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

      在这里插入图片描述

    3. 查询不同的Mapper.xml

    4. 手动清理缓存

      sqlSession.clearCache();//手动清理缓存
      在这里插入图片描述

小结:

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

即从SqlSessionFactory.openSession()到SqlSession.close()这个区间段

一级缓存相当(就是)于一个Map

13.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个命名空间,对应一个二级缓存
  • 工作机制:
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中

步骤:

  1. 开启全局缓存

     <setting name = "cacheEnable" value = "true" />
    
  2. 在要使用二级缓存的Mapper中开启
    <cache/>
    也可以自定义一些参数

    <!--在当前Mapper.xml中开启二级缓存
        eviction:文件读写方式
        flushInterval:每隔多少毫秒刷新一次
        size:容量
        readOnly:是否只读
    -->
    <cache eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"
    />
    
  3. 测试:
    问题:我们需要将实体类序列化!否则就会报错!
    caused by java.io.NotSerializableException

    测试类:

    import com.NanCheng.mapper.UserMapper;
    import com.NanCheng.pojo.User;
    import com.NanCheng.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    
    public class MyTest {
        @Test
        public void test(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            SqlSession sqlSession2 = MybatisUtils.getSqlSession();
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
            //查询
            User user1 = mapper.queryUserById(2);
            System.out.println(user1);
    //        //修改
    //       // mapper.updateUser(new User(2,"傻逼","111"));
    //        sqlSession.clearCache();//手动清理缓存
    //        System.out.println("————————————————————————");
    //        //再次查询
            User user2 = mapper2.queryUserById(2);
            System.out.println(user2);
    
    
            sqlSession.close();
            sqlSession2.close();
        }
    }
    
    

    未开启二级缓存:
    在这里插入图片描述

    开启二级缓存后:
    在这里插入图片描述

小结:

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

13.5、缓存原理

在这里插入图片描述

13.6自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存。

要在程序中使用ehcache,要先导包!

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

在mapper中使用我们的ehcache缓存实现

<cache type="org.mybatis.caches.ehcache.EhcacheCache"
/>

ehcache.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false" >
<!--
    diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置,参数详解如下:
    user.home - 用户主目录
    user.dir - 用户当前工作目录
    java.io.tmpdir - 默认临时文件路径
-->
    <diskStore path="./tmpdir/Tmp_EhCache"/>
    
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"
        />
    <cache
        name="cloud_user"
        eternal="false"
        maxElementsInMemory="5000"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LRU"/>
<!--
    defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略,只能定义一个
-->
<!--
    name:缓存名称
    maxElementsInMemory:缓存最大数目
    maxElementsOnDisk:硬盘中最大缓存个数
    eternal:对象是否永久有效,一旦设置了timeout将不起作用
    overflowToDisk:当系统宕机时,是否保存到磁盘
    timeToLiveSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用。可选属性,默认值是0
    timeToIdleSeconds:最大的发呆时间
    diskPersistent: 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。
    diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。
    diskSpoolBufferSizeMB: DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
    memoryStoreEvictionPolicy: 如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。
    1、FIFO ,first in first out (先进先出).
    2、LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
    3、LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。



-->

</ehcache>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>

在mapper中使用我们的ehcache缓存实现

```xml
<cache type="org.mybatis.caches.ehcache.EhcacheCache"
/>
```

ehcache.xml

```xml
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false" >
<!--
    diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置,参数详解如下:
    user.home - 用户主目录
    user.dir - 用户当前工作目录
    java.io.tmpdir - 默认临时文件路径
-->
    <diskStore path="./tmpdir/Tmp_EhCache"/>
    
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"
        />
    <cache
        name="cloud_user"
        eternal="false"
        maxElementsInMemory="5000"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LRU"/>
<!--
    defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略,只能定义一个
-->
<!--
    name:缓存名称
    maxElementsInMemory:缓存最大数目
    maxElementsOnDisk:硬盘中最大缓存个数
    eternal:对象是否永久有效,一旦设置了timeout将不起作用
    overflowToDisk:当系统宕机时,是否保存到磁盘
    timeToLiveSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用。可选属性,默认值是0
    timeToIdleSeconds:最大的发呆时间
    diskPersistent: 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。
    diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。
    diskSpoolBufferSizeMB: DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
    memoryStoreEvictionPolicy: 如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。
    1、FIFO ,first in first out (先进先出).
    2、LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
    3、LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。



-->

</ehcache>
```

Redis数据库来做缓存! K  - V键值对储存

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值