MyBatis

Mybatis-9.28

环境:jdk1.8、mysql8.0、maven3.6.3、idea

简介

image-20211221100203158

MyBatis 是一款优秀的持久层框架

它支持自定义 SQL、存储过程以及高级映射。

MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(实体类)为数据库中的记录。

2013年11月迁移到Github。

如何获得MyBatis

maven仓库:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.8</version>
</dependency>

中文文档:https://mybatis.org/mybatis-3/zh/index.html

GitHub: https://github.com/mybatis/mybatis-3

持久层

数据持久化:持久化就是将程序在持久状态和瞬时状态转化的过程。内存:断电即失

持久层:完成持久化工作的代码块。

优点:简单易学、灵活;解除sql与程序代码的耦合,提高了可维护性;提供映射标签,支持对象与数据库的orm字段关系映射;提供对象关系映射标签,支持对象关系组建维护;提供xml标签,支持编写动态sql。

第一个MyBatis程序

环境

创建数据库:

mysql> create database mybatis;
mysql> use mybatis;
mysql> create table user(
    -> id int(20) NOT NULL,
    -> name varchar(30) DEFAULT NULL,
    -> pwd varchar(30) DEFAULT NULL,
    -> PRIMARY KEY(id)
    -> )ENGINE=INNODB DEFAULT CHARSET=utf8;
mysql> insert into user (id,name,pwd) values
    -> (1,'张三','123456'),
    -> (2,'李四','123456'),
    -> (3,'王五','123890');

新建maven项目:

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

  2. 删除src目录

  3. 导入maven依赖

    <!--    导入依赖-->
        <dependencies>
    <!--        mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
    <!--        mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.8</version>
            </dependency>
    <!--        junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    
        </dependencies>
    

创建模块

编写mybatis的核心配置文件

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<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=UTF-8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="201314"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--    每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>

</configuration>

编写mybatis工具类

package com.wang.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 getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

编写代码

  • 实体类
package com.wang.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 + '\'' +
                '}';
    }
}
  • Dao接口
package com.wang.dao;

import com.wang.pojo.User;
import java.util.List;

public interface UserMapper {
    List<User> getUserList();
}
  • 接口实现类(由原来的UserDaoImpl转变为一个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.wang.dao.UserMapper">

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

测试

编写测试代码UserMapperTest:

package com.wang.dao;

import com.wang.pojo.User;
import com.wang.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
        //方式一
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.getUserList();
        
        for (User user : list) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
}

运行:

image-20220127085453804

Maven由于它的约定大于配置,可遇到我们写的配置文件无法被导出或生效的问题,需要手动配置资源过滤,解决方案:

<!--在build中配置resources来防止我们资源导出失败问题-->        
		<build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                   <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                   </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>

添加到pom.xml文件中。

目录结构如下:

image-20220127091243254

刷新Maven配置,运行测试代码,运行结果:

image-20220127091349013

//        方式二
          List<User> list= sqlSession.selectList("com.wang.dao.UserMapper.getUserList");

image-20220127093205093

注意点:

1.在之前版本的 MyBatis 中,命名空间(Namespaces)的作用并不大,是可选的。但现在,随着命名空间越发重要,你 必须指定命名空间

2.命名规则,使用完全限定名(比如 “com.mypackage.MyMapper.selectAllThings)

3.SqlSessionFactoryBuilder 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了;

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例;

SqlSession 每个线程都应该有它自己的 SqlSession 实例

CRUD

namespaces

namespace中的包名要与接口的包名一致!

select

查询语句:

  • id:就是对应的namespace中的方法名;

  • resultType:Sql语句执行的返回值!

  • parameterType:参数类型

新建查询

只需修改UserMapper.javaUserMapper.xmlUserMapperTest.java这三个文件

UserMapper.java

package com.wang.dao;

import com.wang.pojo.User;
import java.util.List;

public interface UserMapper {
    //查询全部用户
    List<User> getUserList();

    //根据id查询用户
    User getUserById(int id);

}

UserMapper.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">

<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.wang.dao.UserMapper">
<!--    查询语句-->
<!--    查询所有用户-->
    <select id="getUserList" resultType="com.wang.pojo.User">
        select * from mybatis.user
    </select>

<!--    根据id查询用户-->
    <select id="getUserById" resultType="com.wang.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
    
</mapper>

UserMapperTest.java:

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);	//查询1号用户
        System.out.println(user);

        sqlSession.close();
    }

运行结果:

image-20220127100345163

添加用户

UserMapper.java

	//insert新增用户
    int addUser(User user);

UserMapper.xml:

<!--    新增用户-->
<!--    对象中的属性,可以直接取出来-->
    <insert id="addUser" parameterType="com.wang.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>

UserMapperTest.java:

    //增删改需要提交事务
    @Test
    public void test03(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int rs = mapper.addUser(new User(4, "赵六", "222333"));
        //提交事务
        sqlSession.commit();
        if(rs>0){
            System.out.println("插入成功!");
        }

        sqlSession.close();
    }

运行结果:

image-20220127103840299

image-20220127103859023

修改用户

UserMapper.java:

    //update修改用户
    int updateUser(User user);

UserMapper.xml:

<!--    修改用户-->
    <update id="updateUser" parameterType="com.wang.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>

UserMapperTest.java:

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"赵六","123456"));
        sqlSession.commit();
        
        sqlSession.close();
    }

运行结果:

image-20220127111600147

删除用户

UserMapper.java:

    //delete删除用户
    int deleteUser(int id);

UserMapper.xml:

<!--    删除用户-->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>

UserMapperTest.java:

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(3);
        sqlSession.commit();

        sqlSession.close();
    }

运行结果:

image-20220127112417310

注意点:

增删改需要提交事务!

万能的Map

UserMapper.java:

    //万能的Map
    int updateUser2(Map<String,Object> map);

UserMapper.xml:

    <update id="updateUser2" parameterType="map">
        update mybatis.user set pwd=#{password} where id=#{userid};
    </update>

UserMapperTest.java:

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",4);
        map.put("password","111111");
        mapper.updateUser2(map);
        sqlSession.commit();

        sqlSession.close();
    }

运行结果:

image-20220127142421534

实体类或数据库中的表、字段或者参数过多,可以考虑使用Map!

Map传递参数,直接在sql中取出key即可

对象传递参数,直接在sql中取对象的属性即可

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

模糊查询

UserMapper.java:

    //模糊查询
    List<User> getUserLike(String value);

UserMapper.xml:

<!--    模糊查询-->
    <select id="getUserLike" resultType="com.wang.pojo.User">
        select * from mybatis.user where pwd like #{value};
    </select>

UserMapperTest.java:

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

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserLike("%123%");//通配符添加在这里可以防止
        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();
    }

运行结果:

image-20220127144539870

配置解析

核心配置文件

environments(环境配置)

  • mybatis-config.xml

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

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

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

在mybatis-config.xml中切换环境:

<environments default="test">
    <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?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
            <property name="username" value="root"/>
            <property name="password" value="201314"/>
        </dataSource>
    </environment>

</environments>

transactionManager(事务管理器)

MyBatis 中有两种类型的事务管理器:type="[JDBC|MANAGED]"

JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。

MANAGED – 这个配置几乎没做什么

如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖前面的配置。

dataSource(数据源)

使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。

MyBatis默认的事务管理器就是JDBC,连接池:POOLED,学会使用配置多套运行环境

属性(properties)

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

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

db.properties:

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

在核心配置文件中引入

<!--引入外部配置文件    -->
<properties resource="db.properties"/>

<environments default="test">

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

</environments>
<properties resource="db.properties">
    <property name="username" value="root"/>
    <property name="password" value="201314"/>
</properties>
  • 可以直接引入外部文件

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

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

类型别名(typeAliases)

类型别名是为Java类型设置一个短的名字。存在的意义仅在于用来减少类完全限定名的冗余。

<!--    给实体类设置别名-->
<typeAliases>
    <typeAlias type="com.wang.pojo.User" alias="User"/>
</typeAliases>

也可以指定一个包名,MyBatis会在包名下面扫描实体类的包,它的默认别名就为这个类的类名(首字母小写)

<typeAliases>
    <package name="com.wang.pojo"/>
</typeAliases>

在实体类比较少的时候使用第一种。

如果实体类较多,推荐使用第二种,配合实体类的注解@Alias

image-20220128092738509

映射器(mappers)

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

方式一:resource

将UserMapper.xml存放到resources文件夹内,能正常读取

image-20220128102011808

配置如下:
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>

将UserMapper.xml存放到dao文件夹中,存在以下报错:

image-20220128102201730

配置如下:
    <mappers>
        <mapper resource="com/wang/dao/UserMapper.xml"/>
    </mappers>

image-20220128102251862

从报错信息中可以看到,是UserMapper.xml的头文件UTF-8出现错误,去掉中间-,改为UTF8

image-20220128102441721

问题解决!!

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

配置如下:
    <mappers>
        <mapper class="com.wang.dao.UserMapper"/>
    </mappers>

注意点:

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

方式三:package

    <mappers>
        <package name="com.wang.dao"/>
    </mappers>
  • 接口和它的Mapper配置文件必须同名!
  • 接口和它的Mapper配置文件必须在同一个包下

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

数据库中的字段:

image-20220128140718246

拷贝之前的字段,测试实体类字段不一致的情况

@Alias("test")
public class User {
    private int id;
    private String username;
    private String password;
}

根据id查询用户,运行结果:

image-20220128141355048

分析原因:

//	select * from mybatis.user where id = #{id}
//	类型处理器
//	select id,name,pwd from mybatis.user where id = #{id}

解决方法:

  • 起别名

    <select id="getUserById" resultType="test" parameterType="int">
        select id,name as username,pwd as password from mybatis.user where id = #{id};
    </select>
    
  • 结果集映射(resultMap)

<!--    结果集映射-->
    <resultMap id="UserMap" type="test">
<!--        colum数据库中的字段,property实体类中的属性-->
        <result column="name" property="username"/>
        <result column="pwd" property="password"/>
    </resultMap>

<!--    根据id查询用户-->
    <select id="getUserById" resultMap="UserMap">
        select * from mybatis.user where id = #{id};
    </select>

image-20220128142723073

resultMap元素是MyBatis中最重要最强大的元素

设计思想:对于简单的语句不需要配置显式的结果映射,而对于复杂一点的语句,只需要描述它们的关系

日志

Mybatis 通过使用内置的日志工厂提供日志功能。

你可以通过在 MyBatis 配置文件 mybatis-config.xml 里面添加一项 setting 来选择其它日志实现。

可选的值有:SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、 NO_LOGGING,或者是实现了 org.apache.ibatis.logging.Log 接口,且构造方法以字符串为参数的类完全限定名。

STDOUT_LOGGING标准日志输出

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

image-20220129152949143

Log4j

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件。

我们可以控制每一条日志的输出格式。

通过定义每一条日志信息的级别,能够更加细致地控制日志的生成过程。

1.导入log4j包

<!--        log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

2.log4j.properties

### set log levels ###
log4j.rootLogger = DEBUG,console,file

### console 控制台输出的相关设置###
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 = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n

### log file 文件输出的相关设置###
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = ./log/wang.log
log4j.appender.file.MaxFileSize = 10mb
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n

### 日志输出级别 ###
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

3.配置log4j为日志的实现

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

测试运行:

image-20220129162701547

简单使用:

1.在要使用Log4j的类中导入包:import org.apache.log4j.Logger;

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

static Logger logger = Logger.getLogger(UserMapperTest.class);
    @Test
    public void test03(){
        //r
        logger.info("info:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");
    }

image-20220129163705828

分页

使用Limit分页

语法:select * from user limit startIndex,pageSize;
select * from user limit 3;		#[0,n]

使用MyBatis实现分页,核心SQL

1.UserMapper.java接口

//实现分页
List<User> getUserByLimit(Map<String,Integer> map);

2.UserMapper.xml

<!--    实现分页查询-->
<!--    resultMap指向结果集映射-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from mybatis.user limit #{startIndex},#{pageSize};
    </select>

3.测试

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

    HashMap<String, Integer> map = new HashMap<String,Integer>();
    map.put("startIndex",0);
    map.put("pageSize",2);

    List<User> userList = mapper.getUserByLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }

    sqlSession.close();
}

运行结果:

image-20220208104507067

RowBounds分页

接口:

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

UserMapper.xml

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

测试:

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

    //通过java代码层面实现分页
    RowBounds rowBounds = new RowBounds(1, 2);
    List<User> userList = sqlSession.selectList("com.wang.dao.UserMapper.getUserByRowBounds",null,rowBounds);

    for (User user : userList) {
        System.out.println(user);
    }

    sqlSession.close();
}

运行结果:

image-20220208110011496

分页插件

image-20220208110540812

使用注解开发

面向接口编程

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

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

使用注解

1.注解在接口上实现

@Select("select * from user")
List<User> getUsers();

2.需要在核心配置文件中绑定接口

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

3.测试

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

运行结果:

image-20220211091423881

CRUD

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

//设置自动提交为ture
public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

接口:

@Select("select * from user where id = #{id}")
//方法存在多个参数,所有参数前必须加上@Param
User getUserByID(@Param("id") int id);

测试:

@Test
public void test02(){

    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    User userByID = mapper.getUserByID(1);
    System.out.println(userByID);

    sqlSession.close();
}

运行结果:

image-20220211104826211

接口:

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

测试:

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

    mapper.addUser(new User(5,"bushi","123123"));

    sqlSession.close();
}

运行结果:

image-20220211104632096

image-20220211105257216

接口:

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

测试:

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

    mapper.updateUser(new User(5,"yes","222333"));

    sqlSession.close();
}

运行结果:

image-20220211105745009

接口:

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

测试:

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

    mapper.deleteUser(5);

    sqlSession.close();
}

image-20220211110109665

注意:

必须要将接口注册绑定到核心配置文件中!

关于@Param()注解

  • 基本类型的参数或String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型,还是建议加上
  • 在SQL中引用的就是@Param()中设定的属性名

Lombok

导入依赖:

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
</dependencies>

image-20220214084118130

Features
@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

image-20220214091234652

@Data:无参构造、get、set、tostring、hashcode、equals

@AllArgsConstructor:有参构造

@NoArgsConstructor:无参构造

使用步骤:

1.在idea中安装Lombok插件

2.在项目中导入依赖

3.在实体类上添加注解:

package com.wang.pojo;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
//实体类
@Alias("test")
public class User {
    private int id;
    private String username;
    private String password;
}

image-20220214090749478

Lombok的优缺点:

优点:

​ 1.能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率

​ 2.让代码变得更简洁,不用过多的去关注相应的方法

​ 3.属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等

缺点:

​ 1.不支持多种参数构造器的重载

​ 2.虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度

复杂查询环境

新建SQL:

mysql> create table `teacher`(
    -> `id` int(10) NOT NULL,
    -> `name` varchar(30) DEFAULT NULL,
    -> PRIMARY KEY(`id`)
    -> )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
mysql> insert into teacher(`id`,`name`) values (1,'秦老师');

mysql> 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;
    
mysql> insert into `student` (`id`,`name`,`tid`) values ('1','小明','1');

mysql> insert into `student` (`id`,`name`,`tid`) values ('2','小红','1');

mysql> insert into `student` (`id`,`name`,`tid`) values ('3','小张','1');

mysql> insert into `student` (`id`,`name`,`tid`) values ('4','小李','1');

mysql> insert into `student` (`id`,`name`,`tid`) values ('5','小王','1');

新建项目mybatis-05,删除dao和实体类,保留Lombok依赖

image-20220214094925343

在pojo中新建Teacher、Student实体类:

package com.wang.pojo;

import lombok.Data;

@Data
public class Teacher {
    private int id;
    private String name;
}
package com.wang.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;

    //学生需要关联一个老师
    private Teacher teacher;

}

创建对应接口:

package com.wang.dao;

public interface TeacherMapper {
}
package com.wang.dao;

public interface StudentMapper {
}

对应xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wang.dao.StudentMapper">

</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wang.dao.TeacherMapper">

</mapper>

在核心配置文件中注册:

<?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>

<!--引入外部配置文件    -->
    <properties resource="db.properties">
<!--        <property name="username" value="root"/>-->
<!--        <property name="password" value="201314"/>-->
    </properties>
    
<!--    日志工厂-->
    <settings>
<!--        常用配置-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="test">
        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    
<!--    注册-->
    <mappers>
        <mapper resource="StudentMapper.xml"/>
        <mapper resource="TeacherMapper.xml"/>
    </mappers>

</configuration>

测试:

teacher接口:

@Select("select * from teacher where id=#{tid}")
Teacher getTeacher(@Param("tid") int id);

新建测试:

@Test
public void test01(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
    Teacher teacher = mapper.getTeacher(1);
    System.out.println(teacher);

    sqlSession.close();

}

运行结果:

image-20220214101550838

环境搭建完成!

多对一

查询所有的学生信息,以及对应的老师的信息

对应查询语句

select s.id,s.name,t.name from student s,teacher t where s.tid=t.id;

image-20220214143645262

方式一:按照查询嵌套处理(子查询)

Student接口:

//查询所有的学生信息,以及对应的老师的信息
public List<Student> getStudent();

StudentMapper.xml:

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

<select id="getStudent" resultMap="Student">
    select * from student;
</select>

<resultMap id="Student" type="com.wang.pojo.Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--        复杂的属性,我们要单独处理
            对象:association
            集合:collection-->
    <association property="teacher" column="tid" javaType="com.wang.pojo.Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="com.wang.pojo.Teacher">
    select * from teacher where id =#{id};
</select>

测试代码:

@Test
public void test02(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> studentList = mapper.getStudent();
    for (Student student: studentList) {
        System.out.println(student);
    }

    sqlSession.close();
}

运行结果:

image-20220214144107448

方式二:按照结果嵌套处理(联表查询)

接口:

public List<Student> getStudent2();

studentMapper.xml:

<!--    按照嵌套查询结果-->
<select id="getStudent2" resultMap="Student2">
    select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id;
</select>

<resultMap id="Student2" type="com.wang.pojo.Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="com.wang.pojo.Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

测试:

@Test
public void test03(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> studentList = mapper.getStudent2();
    for (Student student: studentList) {
        System.out.println(student);
    }

    sqlSession.close();
}

运行结果:

image-20220214145406762

一对多

获取指定老师下的所有学生及老师的信息。对应查询语句:

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=1;

image-20220215131349412

环境与上面一样。

实体类:

@Data
public class Teacher {
    private int id;
    private String name;

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

teacherMapper.xml:

<!--    按结果嵌套查询-->
<select id="getTeacher" resultMap="Teacher">
    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>

<resultMap id="Teacher" type="com.wang.pojo.Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--        复杂属性单独处理 对象:association 集合:collection
            javaType="" 指定属性类型
            集合中的泛型信息,我们使用ofType获取-->
    <collection property="students" ofType="com.wang.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="tname"/>
        <result property="tid" column="tid"/>
    </collection>

</resultMap>

测试:

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

    Teacher teacher = mapper.getTeacher(1);
    System.out.println(teacher);

    sqlSession.close();

}

运行结果:

image-20220215132544186

动态SQL

指根据不同的条件生成不同的SQL语句

动态SQL元素和JSTL或基于类似XML的文本处理器相似。

  • 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;

创建一个基础工程:

编写实体类

@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime;    //属性名和字段名不一致
    private int views;
}

在配置文件中开启驼峰命名转换
    <setting name="mapUnderscoreToCamelCase" value="true"/>

编写IDUtils

public class IDUtils {

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

插入数据:

接口:
    //插入数据
    int addBlog(Blog blog);

BlogMapper.xml:
    <insert id="addBlog" parameterType="blog">
        insert into mybatis.blog(id,title,author,create_time,views)
        values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
        
测试:
        @Test
    public void test01(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("mybatis如此简单");
        blog.setAuthor("wang");
        blog.setCreateTime(new Date());
        blog.setViews(9999);
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("java如此简单");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("Spring如此简单");
        mapper.addBlog(blog);

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

        sqlSession.close();
    }

运行结果:

image-20220216090224365

if语句

接口:

//查询博客
List<Blog> queryBlogIF(Map map);

BlogMapper.xml:

<select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
-- where元素只在至少有一个子元素的条件返回SQL子句的情况下才去插入"WHERE"子句,若子句的开头有"AND"或"OR",where元素也会将它们移除
        <where>
            <if test="title != null">
                title=#{title}
            </if>
            <if test="author!=null">
                and author=#{author}
            </if>
        </where>
</select>

测试:

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

    HashMap map = new HashMap();
    map.put("title","java如此简单");
    //map.put("author","wang");

    List<Blog> blogs = mapper.queryBlogIF(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();

}

运行结果:

image-20220216101152675

choose(when,otherwise)

接口:

List<Blog> queryBlogChoose(Map map);

BlogMapper.xml:

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

</select>

测试:

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

    HashMap map = new HashMap();
    //至少传一个值
    map.put("title","java如此简单");
    //map.put("author","wang");
    //map.put("views",9999);

    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}

运行结果:

image-20220216103502807

trim(where,set)

接口:

//更新博客
int updateBlog(Map map);

BlogMapper.xml:

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        -- set元素会动态前置SET关键字,同时也会删除无关的逗号,因为用了条件语句之后很可能会在生成的SQL语句的后面留下这些逗号
        <if test="title!=null">
            title=#{title},
        </if>
        <if test="author!=null">
            author=#{author},
        </if>
        <if test="views!=null">
            views=#{views}
        </if>
    </set>
    where id = #{id}
</update>

测试:

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

    HashMap map = new HashMap();
    map.put("title","mybatis如此简单");
    map.put("author","张三");
    map.put("views",1000);
    map.put("id","3c4355e0f0904dcdb0613d3d069f1785");

    mapper.updateBlog(map);

    sqlSession.close();
}

运行结果:

image-20220216105524859

image-20220216105551415

我们可以通过自定义trim元素来定制元素的功能,比如:

定制where元素的功能:
    <trim prefix="WHERE" prefixOverrides="AND|OR">
    ...
	</trim>
定制set元素:
    <trim prefix="set" prefixOverrides=","
    ...
    </trim>

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

SQL片段

有的时候我们会将一些公共的部分抽取出来,实现代码复用。例如:

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

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

运行结果:

image-20220218095734998

注意事项:

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

foreach

查询第1,2,3号用户的id。

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

新建User实体类:

package com.wang.pojo;

import lombok.Data;

@Data
//实体类
public class User {
    private int id;
    private String name;
    private String pwd;

}

BlogMapper接口:

//查询第1,2,3号用户的记录
List<User> queryUserForeach(Map map);

BlogMapper.xml:

<select id="queryUserForeach" parameterType="map" resultType="com.wang.poji.User">
    -- select * from user where (id=1 or id=2 or id=3)
    select * from mybatis.user
    <where>
        <foreach collection="ids" item="id" open="(" separator="or" close=")">
            id=#{id}
        </foreach>
    </where>

</select>

测试:

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

    HashMap map = new HashMap();

    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    //ids.add(2);
    map.put("ids",ids);
    List<User> users = mapper.queryUserForeach(map);
    for (User user : users) {
        System.out.println(user);
    }

    sqlSession.close();
}

运行结果:

image-20220218111429912

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性就行了

缓存

什么是缓存?

存在内存中的临时文件。将用户经常查询的数据放入缓存中,使得查询数据不再需要从磁盘中查询,而从缓存中查询,从而提高查询效率,解决高并发系统的性能问题。

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

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

一级缓存

新建项目,使用user表。

测试步骤:

1.开启日志

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

3.查看日志输出

package com.wang.pojo;

import lombok.Data;

@Data
//实体类
public class User {
    private int id;
    private String name;
    private String pwd;

}

接口:

User queryUserById(@Param("id") int id);

UserMapper.xml:

<select id="queryUserById" resultType="user">
    select * from mybatis.user where id =#{id}
</select>

测试代码:

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

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

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

    sqlSession.close();
}

运行:

image-20220218121601330

缓存失效情况:

  • 映射语句文件中的所有select语句的结果会被缓存

  • 映射语句文件中所有insert、update和delete语句会刷新缓存

  • 缓存会使用最近最少使用算法(LRU)来清除不需要的缓存

  • 手动清理缓存

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

    User user1 = mapper.queryUserById(1);
    System.out.println(user1);
    System.out.println("======================");
    //在查询完1号用户后修改2号用户
    mapper.updateUser(new User(2,"aaa","bbbbbb"));
    //手动清理缓存
    //sqlSession.clearCache();
    System.out.println("======================");
    User user2 = mapper.queryUserById(1);
    System.out.println(user2);

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

    sqlSession.close();
}

结果:

image-20220218123006458

小结:一级缓存默认开启,只在一次SqlSession中有效,无法关闭,可手动清理。

二级缓存

工作机制:开启二级缓存后,一个会话查询一条数据,这个数据会被放在当前会话的一级缓存中,会话关闭后,一级缓存中的数据会被保存到二级缓存中,新的会话查询信息就可以从二级缓存中获取内容。

不同的mapper查出的数据会放到自己对应的缓存(map)中。

使用步骤:

1.开启全局缓存

<!--        显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>

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

<!--在当前mapper.xml中使用二级缓存-->
<cache/>

也可以自定义参数

<cache
       eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"
       />

缓存策略FIFO(先进先出),每隔60s刷新,最多存储512个引用,返回的对象被认为是仅可读。

3.测试

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

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.queryUserById(1);
    System.out.println(user);
    sqlSession.close();		//关闭第一个SqlSession

    UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
    User user2 = mapper2.queryUserById(1);
    System.out.println(user2);
    sqlSession2.close();
}

运行结果:

image-20220218130246828

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

自定义缓存Ehcache

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

导入依赖:

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>

开启自定义缓存:

<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="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当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"/>
    <!--
          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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
       -->
</ehcache>

当前常用Redis数据库来做缓存!!!

posted @ 2022-01-28 14:49  萘汝  阅读(39)  评论(0编辑  收藏  举报
我发了疯似的祝你好!