Mybatis

目录

1.简介

1.MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。

2.SqlSession创建流程

(1)SqlSessionFactoryBuilder 读取xml文件/configuration实例

(2)SqlSessionFactory SqlSessionFactoryBuilder.bulid()方法创建实例

(3)SqlSession SqlSessionFactory.openSession()方法创建实例

(4)SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。

3.获取SqlSessionFactoryBuilder实例的两种方法

2. Mybatis第一个程序

思路:搭建环境-->导入Mybatis-->编写代码-->测试

1搭建环境

搭建数据库

2.1.新建项目

1.新建一个普通的maven项目

2.删掉src目录

3.导入maven依赖

<dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.19</version>
            </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.2.创建一个模块

编写mybatis核心配置文件--mybatis-config.xml

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=Utf8&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="zh123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个Mapper.xml都需要在Mybatis文件中注册-->
    <mappers>
        <mapper resource="com/zh/dao/UserMapper.xml"/>
    </mappers>
</configuration>

编写mybatis工具类

/**
 * 工具类
 * 获取sqlSession对象
 * sqlSessinFactory-->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 getSqlSession () {
             //SqlSession sqlSession = sqlSessionFactory.openSession(true);//自动提交
             //return sqlSession;
            return sqlSessionFactory.openSession();
         }
}

2.3.编写代码

实体类

//实体类
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 + '\'' +
                '}';
    }
}

接口

public interface UseDao {
    List<User> getUserList();
}

接口实现类

<?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.zh.dao.UseDao">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.zh.pojo.User">
    select * from mybatis.user
  </select>
</mapper>

2.4测试

junit测试

public class UserDaoTest {
    @Test
    public void test() {
        //第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            //执行SQL
            //方式一:getMapper
            UseDao useDao = sqlSession.getMapper(UseDao.class);
            List<User> userList = useDao.getUserList();
            //方法二:
            // List<User> userList = sqlSession.selectList("com.zh.dao.UseDao.getUserList");

            for (User user : userList) {
                System.out.println(user);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }finally {
            //关闭sqlSessiion
            sqlSession.close();
        }


        }
}

可能会遇到的问题:

1.配置文件没有注册

 <mappers>
        <mapper resource="com/zh/dao/UserMapper.xml"/>
    </mappers>

2.绑定接口错误

<mapper namespace="com.zh.dao.UseDao">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.zh.pojo.User">
    select * from mybatis.user
  </select>

3.方法名不对

public static SqlSession getSqlSession () {
             //SqlSession sqlSession = sqlSessionFactory.openSession();
             //return sqlSession;
            return sqlSessionFactory.openSession();
         }

4.返回类型不对

5.资源过滤

在pom.xml中加入以下代码

 <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</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>

项目结构

|-- mybatis-01
        |-- mybatis-01.iml
        |-- pom.xml
        |-- src
        |   |-- main
        |   |   |-- java
        |   |   |   |-- com
        |   |   |       |-- sky
        |   |   |           |-- dao
        |   |   |           |   |-- UserMapper.java 
        |   |   |           |   |-- UserMapper.xml 
        |   |   |           |-- pojo
        |   |   |           |   |-- User.java
        |   |   |           |-- utils
        |   |   |               |-- MybatisUtils.java
        |   |   |-- resources
        |   |       |-- mybatis-config.xml
        |   |-- test
        |       |-- java
        |           |-- com
        |               |-- sky
        |                   |-- dao
        |                       |-- UserMapperTest.java

3.CURD


1.namespace

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

2.select

选择查询语句

  • id:就是对应的namespace中的方法
  • resultType:sql语句执行的返回值
  • parmeterType:参数类型
//查询全部用户
 List<User> getUserList();
 //根据ID查询用户
 User getUserById(int id);
  <!--select查询语句-->
    <select id="getUserList" resultType="com.zh.pojo.User">
    select * from mybatis.user
  </select>
<!--根据id查询用户-->
    <select id="getUserById" resultType="com.zh.pojo.User" parameterType="int">
        select*from mybatis.user where id=#{id}
    </select>
@Test
public void getUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UseMapper mapper = sqlSession.getMapper(UseMapper.class);
    User user = mapper.getUserById(1);
    System.out.println(user);

    sqlSession.close();
}

3.insert

 //inser一个用户
    int addUser(User user);
    //修改数据
<!--插入语句-->
    <insert id="addUser" parameterType="com.zh.pojo.User">
        <!--参数类型是实例时,写全栈类名-->
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
//增
@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UseMapper mapper = sqlSession.getMapper(UseMapper.class);
    int user = mapper.addUser(new User(4, "zhe", "1122"));
    if (user>0){
        System.out.println("提交成功");
    }
        sqlSession.commit ();
        sqlSession.close();

4.update

  //修改数据
int updateUser(User user);
 <!--修改语句-->
<update id="updateUser" parameterType="com.zh.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
@Test
public void updateUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UseMapper mapper = sqlSession.getMapper(UseMapper.class);
    int user = mapper.updateUser(new User(4,"123","741785"));
    System.out.println(user);
    sqlSession.commit ();
    sqlSession.close();
}

5.delete

   //删除一个用户
int deleteUser(int id);
<!--删除语句-->
<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id=#{id};
</delete>
@Test
public void deleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UseMapper mapper = sqlSession.getMapper(UseMapper.class);
    int user = mapper.deleteUser(4);
    sqlSession.commit();
    sqlSession.close();
}

6.分析错误

sql标签不要匹配错

resource绑定mapper,需要使用路径

程序配置文件必须符合规范

NullPointerException,没有注册到资源

输出的xml文件中存在中文乱码问题

maven资源没有到出问题

7.万能map

假设实体类或数据表中,有多个字段或参数,应该考虑Map

//根据ID查询用户
    User getUserById2(Map<String,Object> map);
<!--测试map-->
<select id="getUserById2" resultType="com.zh.pojo.User" parameterType="map">
    select*from mybatis.user where id=#{useid}
</select>
ublic void getUserByid2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UseMapper mapper = sqlSession.getMapper(UseMapper.class);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("useid",3);
    User byId2 = mapper.getUserById2(map);
    System.out.println(byId2);
    sqlSession.close();
}

Map传递参数,直接在sql中取出key即可 【parameterType="map"】

对象传递参数,直接在sql中取对象的属性即可 【parameterType="Object"】

只有一个基本类型参数的情况下,可以在sql中取到 【parameterType="int"/省略】

多个参数用Map,或者注解

8.模糊查询

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

List<User> userList = mapper.getUserLike("%y%");

2.在sql拼接中使用通配符

4.配置文件

1.核心配置文件

  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

2.环境配置(environments)

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

注:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境

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

3.属性(properties)

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

这些属性都是可以外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可以通过properties元素的子元素来传递

编写一个配置文件

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=Utf8&serverTimezone=Asia/Shanghai
username=root
pwd=zh123456

在核心配置文件中映入

<!--引入外部配置文件-->
<properties resource="db.properties">
    <property name="username" value="root"/>
    <property name="pwd" value="zh123456"/>
</properties>
  • 可以直接引入外部文件

  • 可以在其中增加一些属性配置

  • 如果两个文件中有同一字段,优先使用外部配置文件

4.类型别名(typeAliases)

  • 类型别名是为java类型设置一个短的名字
  • 存在的意义在于用来减少类完全限定名的冗余
  <!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias alias="user" type="com.zh.pojo.User"/>
     <!--指定包名-->
        <!--<package name="com.zh.pojo"/>-->
    </typeAliases>

当使用指定包名时,Mybatis会在包名下面搜索需要的Java Bean,比如:

扫描实体类的包,它的默认别名就为这个类的别名,首字母小写(大写也可以)

在实体类较少的时候,使用类名的方式

实体类较多时,使用第二种

第一种可以自定义别名,第二种不行,如果非要改,需要在实体类上加入注解

//通过注解给实体类起别名
@Alias("HELLO")
public class User {}

5.设置

这是Maybatis中极为重要的调整设置,它们会改变Maybatis的运行时行为

cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true | false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 true | false false
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置

6.其他配置

  • typeHandlers(类型处理器)

  • objectFactory(对象工厂)

  • plugins(插件)

7.映射器(mappers)

每一个Mapper.xml文件都需要在Mybatis核心配置文件中注册

MapperRegistry:注册绑定我们的Mapper文件

方式一:

<mappers>
<mapper resource="com.zh.dao.UseMapper.xml"/>
</mappers>

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

<mappers>
<mapper class="com.zh.dao.UseMapper"/>
</mappers>

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

<mappers>
<package name="com.zh.dao"/>
</mappers>

注:方式二、方式三必须遵循以下

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

8.生命周期和作用域(Scope)

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

SqlSessionFactoryBuilder:

  • 局部变量

  • 一旦创建了SqlSessionFactory,就不再需要它了

SqlSessionFactory:

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

SqlSession

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

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

1.改别名

<select id="selectUsers" resultType="User">
  select
    user_id             as "id",
    user_name           as "userName",
    hashed_password     as "hashedPassword"
  from some_table
  where id = #{id}
</select> 

2.结果集映射

 <resultMap id="UserMap" type="User">
<!--<result column="id" property="id"/>-->
<!--<result column="name" property="name"/>-->
        <result column="pwd" property="password"/>
    </resultMap>
<!--根据id查询用户-->
    <select id="getUserById" resultMap="UserMap" parameterType="int">
           select*from  mybatis.user where id=#{id}
      <!--select id,name,pwd as password from mybatis.user where id=#{id}-->
    </select>
  • ResultMap元素是Mybatis中最重要最强大的元素
  • ResultMap的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了
  • ResultMap最优秀的地方在于。在你相当了解它们时,不需要全部显示的映射(只需要映射不一样的)

6.日志

6.1、日志工厂

如果一个数据库操作,出现了异常,可以利用日志排错
曾经:sout、debug
现在:日志工厂

logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
  • SLF4J

  • LOG4J [掌握]

  • LOG4J2

  • JDK_LOGGING

  • COMMONS_LOGGING

  • STDOUT_LOGGING 【掌握】

  • NO_LOGGING

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

1.STDOUT_LOGGING 标准日志输出

<settings>
        <!--标准的日至工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

2.log4j

1.简介

<settings>
        <!--标准的日至工厂实现-->
        <setting name="logImpl" value="LOG4J"/>
    </settings>

通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,
甚至是套接口服务器、NT的事件记录器、等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,
我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

2.日志的作用

第一用途:编写程序的时候,进行调试。

类似于:大家使用System.out.print()来调试代码

第二用途:项目上线(商业运行),查看系统的运行状态

日志是用来记录信息的,比如服务器的日志主要是用来记录一些访问信息,以便出现状况时,可以根据日志来判断原因。

3.使用

1.导包
<dependencies>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
2.配置log4j.properies文件
### set log levels ###
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/zh.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.在代码中的使用
定义属性:static Logger logger = Logger.getLogger(LogDemo.class); //LogDemo为相关的类
@Test
    public void testLog4j() {
        logger.info("info:test info");
        logger.error("err:进入");
        logger.debug("debug:test debug");
    }

4.日志级别

每个Logger都被了一个日志级别(log level),用来控制日志信息的输出。日志级别从高到低分为:
A:off 最高等级,用于关闭所有日志记录。
B:fatal 指出每个严重的错误事件将会导致应用程序的退出。
C:error 指出虽然发生错误事件,但仍然不影响系统的继续运行。
D:warm 表明会出现潜在的错误情形。
E:info 一般在粗粒度级别上,强调应用程序的运行全程。
F:debug 一般用于细粒度级别上,对调试应用程序非常有帮助。
G:all 最低等级,用于打开所有日志

        logger.info("info:进入了testLogin4j");
        logger.error("err:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");

7.分页

  • 作用:减少数据的处理量
1.使用limit分页
语法:select *from user limit startIndex,pageSize;
select*from user limit 3; #[0,n]
2.使用Mybatis实现分页,核心sql
接口
  List<User>  getUserByLimit(Map<String,Integer> map);
Mapper.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
    select *from mybatis.user limit #{startIndex},#{pageSize}
</select>	
测试
public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",1);
    map.put("pageSize",3);
    List<User> user = mapper.getUserByLimit(map);
    for (User user1 : user) {
        System.out.println(user1);
    }
    sqlSession.close();
}
3.RowBounds分页

不再使用Sql实现分页

1.接口

 List<User> selectByRowBounds();

2.mapper.xml

  <select id="selectByRowBounds" resultMap="userMap">
        select *
        from mybatis.user;
    </select>

3.测试

 public void testRowBounds(){
        RowBounds rowBounds = new RowBounds(0, 3);
        List<User> users = sqlSession.selectList("com.zh.mapper.UserMapper.selectByRowBounds",null,rowBounds);
        for (User user : users) {
            System.out.println(user);
        }
    }

8.使用注解开发

使用注解映射简单语句会使代码更加简洁,但对于复杂语句,使用xml映射

注解curd

接口

 //查询所有用户
    @Select("select*from mybatis.user")
    List<User> selectAll();

    //根据id查询
    //方法存在多个参数时,所有的参数前面必须加上@Param("id")注解
    @Select("select*from user where id=#{id}")
    User getUserById(@Param("id") int id);

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

    //更新
    @Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
    int updateUser(User user);

    @Delete("delete from user where id=#{uid}")
    int deleteUser(@Param("uid") int id);

configure.xml

<mappers>
<mapper class="com.zh.dao.UserMapper"/>
</mappers>

测试

 @Test
    public void selectAll() {
        List<User> users = mapper.selectAll();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void selectById() {
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

    @Test
    public void addUser() {
        int i = mapper.addUser(new User(9, "qwe", "asd"));
        if (i > 0) {
            System.out.println("插入成功");
        }
        sqlSession.close();
    }

    @Test
    public void deleteUser() {
        int i = mapper.deleteUser(9);
        if (i > 0) {
            System.out.println("删除成功");
        }
        sqlSession.close();
    }

    @Test
    public void updateUser() {
        int i = mapper.updateUser(new User(7, "456", "123"));
        if (i > 0) {
            System.out.println("更新成功");
        }
        sqlSession.close();
    }

关于@Param()注解

基本类型的参数或者String类型,需要加上

引用类型不需要加

如果只有一个基本类型的话,可以忽略,但是建议大家都加上

我们在SQL中引用的就是我们这里的@Param()中设定的属性名

#{} ${}区别

${}不能防止sql注入

面向接口编程

关于接口的理解

接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
接口的本身反映了系统设计人员对系统的抽象理解
接口应有两类:
第一类是一个个体的抽象,它可对应为一个抽象体(abstract class);
第二类 是对一个个体某一方面的抽象,即形成一个抽象面(interface);
一个体可能有多个抽象面,抽象体与抽象面是有区别的

三个面向区别

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

mybatis执行流程

img

9.Lombok

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>
@Data
@AllArgsConstructor
@NoArgsConstructor

10.多对一处理

多对一的理解:

  • 多个学生对应一个老师

  • 如果对于学生这边,就是一个多对一的现象,即从学生这边关联一个老师!

img

测试环境搭建:

1.导入lombok

2.新建实体类Teacher,Student

@Data
public class Teacher{
    private int id;
    private String name;
}
@Data
public class Student{
    private int id;
    private String name;
    //多个学生可以是同一个老师,即多对一
    private Teacher teacher;
}

3.建立Mapper接口

public interface StudentMapper{}
public interface TeacherMapper{}

4.建立Mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.StudentMapper">
</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.kuang.mapper.TeacherMapper">
</mapper>

查询方式:

按查询嵌套处理(子查询)

1、给StudentMapper接口增加方法
//获取所有学生及对应老师的信息
public List<Student> getStudents();
2、编写对应的Mapper文件
<!--
	需求:获取所以学生及对应老师的信息
    思路:
        1. 查询所有的学生信息
        2. 根据查询出来的学生的tid,寻找对应的老师!  子查询 
		3.思考问题,这样学生的结果集中应该包含老师,改如何处理,数据库中我们一般使用关联查询?
			1.做一个结果集映射:StudentTeacher
			2.StudentTeacher结果集的属性为Student
			3.学生中老师的属性为teacher,对应数据库中为tid
			多个[1,....]学生关联一个老师=>一对一,一对多
			4.association:一个复杂类型的关联,使用它来处理关联查询
    -->

<select id="getStudents" resultMap="StudentTeacher">
    select * from student
   </select>
   <resultMap id="StudentTeacher" type="Student">
       <!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
       <association property="teacher"  column="tid" javaType="Teacher" select="getTeacher"/>
   </resultMap>
   <!--
   这里传递过来的id,只有一个属性的时候,下面可以写任何值
   association中column多参数配置:
       column="{key=value,key=value}"
       其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
   -->
   <select id="getTeacher" resultType="teacher">
      select * from teacher where id = #{id}
   </select>
3.mybatis-config.xml文件中注册mapper
4.注意点说明:
<resultMap id="StudentTeacher" type="Student">
   <!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
   <association property="teacher"  column="{id=tid,name=tid}" javaType="Teacher" select="getTeacher"/>
</resultMap>
<!--
这里传递过来的id,只有一个属性的时候,下面可以写任何值
association中column多参数配置:
   column="{key=value,key=value}"
   其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
-->
<select id="getTeacher" resultType="teacher">
  select * from teacher where id = #{id} and name = #{name}
</select>
5.测试
@Test
public void testGetStudetns(){
    SqlSession sqlSession=MybatisUntils.getSqlSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);

   List<Student> students = mapper.getStudents();

   for (Student student : students){
       System.out.println(
               "学生名:"+ student.getName()
                       +"\t老师:"+student.getTeacher().getName());
  }
}

按照结果嵌套处理(联表查询)

1.接口方法编写
public List<Student> getStudent2();
2.编写对应的mapper文件
<!--
按查询结果嵌套处理
思路:
	1.直接传出结果,进行结果集的映射
-->
<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
</select>
<resultMap id="StudentfTeacher2" type="Student">
    <id property="id" column="sid"/>
    <result property="name" column="sname"/>
    <!--关联对象property 关联对象在Student实体类中的属性-->
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>
3.测试
@Test
public void testGetStudents2(){
   SqlSession session = MybatisUtils.getSession();
   StudentMapper mapper = session.getMapper(StudentMapper.class);

   List<Student> students = mapper.getStudents2();

   for (Student student : students){
       System.out.println(
               "学生名:"+ student.getName()
                       +"\t老师:"+student.getTeacher().getName());
  }
}

总结:

按照查询进行嵌套处理就像SQL中的子查询
按照结果进行嵌套处理就像SQL中的联表查询

11.一对多处理

一对多理解:

  • 一个老师拥有多个学生

  • 如果对于老师这边,就是一个一对多的现象,即从一个老师下面拥有一群学生(集合)

实体类编写:

@Data
public class Student {
   private int id;
   private String name;
   private int tid;
}
@Data 
public class Teacher {
   private int id;
   private String name;
   //一个老师多个学生
   private List<Student> students;
}

查询方式:

按照结果嵌套处理

1.TeacherMapper接口编写
//获取指定老师,及学生下的所有学生
public Teacher getTeacher(int id);
2.编写接口对应的Mapper配置文件
<mapper namespace="com.kuang.mapper.TeacherMapper">
<!--
思路:
	1.从学生表和老师表中查出学生id,学生姓名,老师姓名
	2.对查询出来的操作做结果集映射
		1.集合的话,使用colleaction
		javaType和ofType都是用来指定对象类型的
		javaType是用来指定pojo中属性的类型
		ofType指定的是映射到list集合属性中pojo的类型
-->
    <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=#{id}
   </select>

   <resultMap id="TeacherStudent" type="Teacher">
       <result  property="name" column="tname"/>
       <collection property="students" ofType="Student">
           <result property="id" column="sid" />
           <result property="name" column="sname" />
           <result property="tid" column="tid" />
       </collection>
   </resultMap>
</mapper>
3.注册Mapper
4.测试
@Test
public void testGetTeacher(){
     SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

按查询嵌套处理

1.TeacherMapper接口编写方法
public Teacher getTeacher2(int id);
2.编写接口对应的Mapper配置文件
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id = #{id}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
   <!--column是一对多的外键 , 写的是一的主键的列名-->
   <collection property="students" javaType="ArrayList" ofType="Student"column="id" select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
  select * from student where tid = #{id}
</select>
3.注册Mapper
4.测试
@Test
public void testGetTeacher2(){
   SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher2(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

小结:

1.关联-association

2.集合-collection

3.所以association用于一对一和多对一,而collection是用于一对多的关系

4.javaType和ofType都是用来指定对象

  • javaType用来指定pojo属性的类型

  • ofTyp指定的是映射到list集合属性中pojo的类型

注意说明:

1.保证SQL的可读性,尽量通俗易懂

2.根据实际要求,尽量编写性能更高的SQL语句

3.注意属性名和字段名不一致的问题

4.注意一对多和多对一中,字段和属性对应的问题

5.尽量使用log4j,通过日志来查看自己的错误

12.动态sql

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

搭建环境

1.新建一个数据库表:blog

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

2.IdUtil工具类

public class IdUtil{
    public static String genId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}

3.实体类编写

@Data
public class Blog{
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

4.编写Mapper接口及xml文件

public interface BlogMapper{}
<?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.kuang.mapper.BlogMapper">
</mapper>

5.mybatis核心配置文件,下划线驼峰自动 转换

<settings>
   <setting name="mapUnderscoreToCamelCase" value="true"/>
   <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--注册Mapper.xml-->
<mappers>
 <mapper resource="mapper/BlogMapper.xml"/>
</mappers>

6.插入初始数据

编写接口

//新增第一个博客
int addBlog(Blog blog);

sql配置文件

<insert id="addBlog" parameterType="blog">
insert into blog (id,title,author,create_time,views) values (#(id),#(title),#(author),#(createTime),#(views))
</insert>

初始化博客方法

@Test
public void addInitBlog(){
    SqlSession SqlSession=MybatisUtils.getSqlSession();
    BlogFMapper mapper=SqlSession.getMapper(BlogMapper.class);

  Blog blog = new Blog();
   blog.setId(IDUtil.genId());
   blog.setTitle("Mybatis如此简单");
   blog.setAuthor("狂神说");
   blog.setCreateTime(new Date());
   blog.setViews(9999);

   mapper.addBlog(blog);

   blog.setId(IDUtil.genId());
   blog.setTitle("Java如此简单");
   mapper.addBlog(blog);

   blog.setId(IDUtil.genId());
   blog.setTitle("Spring如此简单");
   mapper.addBlog(blog);

   blog.setId(IDUtil.genId());
   blog.setTitle("微服务如此简单");
   mapper.addBlog(blog);

   session.close();
}

if语句

需求:根据作者名字和博客名字来查询博客。如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

1.编写接口类

//需求1
List<Blog> queryBlogIf(Map map);

2.编写sql语句

<!--需求1
根据作者名字和博客名字来查询博客
如果作者名字为空,那么只根据博客名字来查询,反之,则根据作者名来查询
select*from blog where title=#{title} and author=#{author}
-->
<select id="queryBlogIf" parameterType="map" resultType="blog">
  select * from blog
    
   <where>
       <if test="title != null">
          title = #{title}
       </if>
       <if test="author != null">
          and author = #{author}
       </if>
   </where>
</select>

3.测试

@Test
public void testQueryBlogIf(){
   SqlSession session = MybatisUtils.getSession();
   BlogMapper mapper = session.getMapper(BlogMapper.class);

   HashMap<String, String> map = new HashMap<String, String>();
   map.put("title","Mybatis如此简单");
   map.put("author","狂神说");
   List<Blog> blogs = mapper.queryBlogIf(map);

   System.out.println(blogs);

   session.close();
}

注:where标签会根据返回值,自动添加删除and或or

set

自动删除子句中逗号

1.编写接口

int updateBlog(Map map);

2.sql配置文件

<!--注意set是用的逗号隔开-->
<update id="updateBlog" parameterType="map">
  update blog
     <set>
         <if test="title != null">
            title = #{title}
         </if>
         <if test="author != null">
            ,author = #{author}
         </if>
     </set>
  where id = #{id};
</update>

3.测试

@Test
public void testUpdateBlog(){
   SqlSession session = MybatisUtils.getSession();
   BlogMapper mapper = session.getMapper(BlogMapper.class);

   HashMap<String, String> map = new HashMap<String, String>();
   map.put("title","动态SQL");
   map.put("author","秦疆");
   map.put("id","9d6a763f5e1347cebda43e2a32687a77");
   mapper.updateBlog(map);
   session.close();
}

choose语句

choose语句相当于switch语句,会执行满足条件的语句

1.编写接口方法

List<Blog> queryBlogChoose(Map map);

2.sql配置文件

<select id="queryBlogChoose" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <choose>
           <when test="title != null">
                title = #{title}
           </when>
           <when test="author != null">
               author = #{author}
           </when>
           <otherwise>
               views = #{views}
           </otherwise>
       </choose>
   </where>
</select>

3.测试类

@Test
public void testQueryBlogChoose(){
   SqlSession session = MybatisUtils.getSession();
   BlogMapper mapper = session.getMapper(BlogMapper.class);

   HashMap<String, Object> map = new HashMap<String, Object>();
   map.put("title","Java如此简单");
   map.put("author","狂神说");
   map.put("views",9999);
   List<Blog> blogs = mapper.queryBlogChoose(map);

   System.out.println(blogs);

   session.close();
}

sql片段

有时候可能某个sql语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用

提取sql片段

<sql id="if-title-author">
   <if test="title != null">
      title = #{title}
   </if>
   <if test="author != null">
      and author = #{author}
   </if>
</sql>

引用sql片段

<select id="queryBlogIf" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
       <include refid="if-title-author"></include>
       <!-- 在这里还可以引用其他的 sql 片段 -->
   </where>
</select>

Foreach

需求:查询blog表中id分别为1,2,3的博客信息

1.编写接口

List<Blog> queryBlogForeach(Map map);

2.编写sql语句

<select id="queryBlogForeach" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <!--
       collection:指定输入对象中的集合属性
       item:每次遍历生成的对象
       open:开始遍历时的拼接字符串
       close:结束时拼接的字符串
       separator:遍历对象之间需要拼接的字符串
       select * from blog and (id=1 or id=2 or id=3)
     -->
       <foreach collection="ids"  item="id" open="and (" close=")" separator="or">
          id=#{id}
       </foreach>
   </where>
</select>

3.测试

@Test
public void testQueryBlogForeach(){
   SqlSession session = MybatisUtils.getSession();
   BlogMapper mapper = session.getMapper(BlogMapper.class);

   HashMap map = new HashMap();
   List<Integer> ids = new ArrayList<Integer>();
   ids.add(1);
   ids.add(2);
   ids.add(3);
   map.put("ids",ids);

   List<Blog> blogs = mapper.queryBlogForeach(map);

   System.out.println(blogs);

   session.close();
}

小结:

其实动态sql语句的编写往往是一个拼接的问题,为了保证拼接准确,我们最好首先写出对应原生的sql语句,然后在通过mybatis动态sql对照着写,防止出错,多在实践中使用才能熟练掌握它的技巧

13.缓存

简介

1.什么是缓存(cache)?

  • 存在内存中的临时数据
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题

2.为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率

3.什么样的数据能使用缓存?

经常查询并且不经常改变的数据

Mybatis缓存

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

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

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存

一级缓存也叫本地缓存:

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

测试

1.在mybatis中加入日志,方便测试结果
2.编写接口方法
//根据id查询用户
User queryUserById(@Param("id") int id);
3.接口对应的Mapper文件
<select id="queryUserById" resultType="user">
  select * from user where id = #{id}
</select>
4.测试
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
}
5.结果分析

一级缓存失效的四种情况:

一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!
1.sqlSession不同
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
   session2.close();
}
结论:每个sqlSession中的缓存相互独立
2、sqlSession相同,查询条件不同
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(2);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
}
结论:当前缓存中,不存在这个数据
3.sqlSession相同,两次查询之间进行了增删改操作
增加方法
//修改用户
int updateUser(Map map);
编写sql
<update id="updateUser" parameterType="map">
  update user set name = #{name} where id = #{id}
</update>
测试
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   HashMap map = new HashMap();
   map.put("name","kuangshen");
   map.put("id",4);
   mapper.updateUser(map);

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}
4、sqlSession相同,手动清除一级缓存
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   session.clearCache();//手动清除缓存

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}
一级缓存就是一个map

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

  • 工作机制

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

使用步骤:

1.开启全局缓存【mybatis-config.xml】

默认为true,可以不开启

<setting name="cacheEnabled" value="true"/>
2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】
<cache/>
<cache
 eviction="FIFO"
 flushInterval="60000"
 size="512"
 readOnly="true"/>
3、代码测试
  • 所有的实体类先实现序列化接口
  • 测试代码
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();

   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   session.close();

   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session2.close();
}

3.自定义缓存-ehcache

1.导包

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

2.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="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
     -->
    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      overflowToDisk:是否保存到磁盘,当系统当机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO,first in first out,这个是大家最熟的,先进先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
      LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <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"/>

</ehcache>

结论

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据

  • 查出的数据都会被默认先放在一级缓存中

  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

posted @ 2021-04-26 11:38  Zh'Blog  阅读(62)  评论(0编辑  收藏  举报