对于MyBatis的理解

一、MyBatis简介

1.1 什么是MyBatis

  1. MyBatis 是一款优秀的持久层框架
  2. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程
  3. MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
  4. MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。
  5. 2013年11月迁移到Github 
  6. Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
  7. GitHub : https://github.com/mybatis/mybatis-3
  8. maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

1.2 持久化

数据持久化是将程序数据在持久状态和瞬时状态间转换的机制。

  1. 即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中、XML数据文件中等等。
  2. JDBC就是一种持久化机制。文件IO也是一种持久化机制。
  3. 在生活中 : 将鲜肉冷藏,吃的时候再解冻的方法也是。将水果做成罐头的方法也是。

为什么需要持久化服务呢?那是由于内存本身的缺陷引起的

  1. 内存断电后数据会丢失,但有一些对象是无论如何都不能丢失的,比如银行账号等,遗憾的是,人们还无法保证内存永不掉电。
  2. 内存过于昂贵,与硬盘、光盘等外存相比,内存的价格要高2~3个数量级,而且维持成本也高,至少需要一直供电吧。所以即使对象不需要永久保存,也会因为内存的容量限制不能一直呆在内存中,需要持久化来缓存到外存。

1.3 持久层

什么是持久层?

  1. 完成持久化工作的代码块 .  ---->  dao层 【DAO (Data Access Object)  数据访问对象】
  2. 大多数情况下特别是企业级应用,数据持久化往往也就意味着将内存中的数据保存到磁盘上加以固化,而持久化的实现过程则大多通过各种关系数据库来完成。
  3. 不过这里有一个字需要特别强调,也就是所谓的“层”。对于应用系统而言,数据持久功能大多是必不可少的组成部分。也就是说,我们的系统中,已经天然的具备了“持久层”概念?也许是,但也许实际情况并非如此。之所以要独立出一个“持久层”的概念,而不是“持久模块”,“持久单元”,也就意味着,我们的系统架构中,应该有一个相对独立的逻辑层面,专注于数据持久化逻辑的实现.
  4. 与系统其他部分相对而言,这个层面应该具有一个较为清晰和严格的逻辑边界。【说白了就是用来操作数据库存在的!】

1.4 为什么需要MyBatis?

  1. Mybatis就是帮助程序猿将数据存入数据库中 , 和从数据库中取数据 .
  2. 传统的jdbc操作 , 有很多重复代码块 .比如 : 数据取出时的封装 , 数据库的建立连接等等... , 通过框架可以减少重复代码,提高开发效率 .
  3. MyBatis 是一个半自动化的ORM框架 (Object Relationship Mapping) -->对象关系映射
  4. 所有的事情,不用Mybatis依旧可以做到,只是用了它,所有实现会更加简单!技术没有高低之分,只有使用这个技术的人有高低之别
  5. MyBatis的优点:
  6. 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件就可以了,易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
  7. 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
  8. 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
  9. 提供xml标签,支持编写动态sql...
  10. 最重要的一点,使用的人多!公司需要!

1.5 MyBatis 程序演示

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

1、搭建数据库

CREATE DATABASE `mybatis`;
 
USE `mybatis`;
 
DROP TABLE IF EXISTS `user`;
 
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;
 
insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

2、删除src目录

3、导入maven依赖

  <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</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.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

4、创建一个Module模块

5、编写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>
    <!--default=“”可选,即可以写多个<environments></environments>-->
    <environments default="development">
        <environment id="development">
            <!--事务管理-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--&amp;转义字符,相当无and-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个mapper.xml文件都需要在mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/han/dao/userMapper.xml"/>
    </mappers>
</configuration>

amp; 是html中的或者url地址栏中的转义字符,就是代表&的意思

比如:url.jdbc=jdbc:mysql://localhost:3306/permissionmdb?useUnicode=true&&characterEncoding=utf8&&serverTimezone=GMT%2B8

还可以这样写(md会转意,所以加了[])
url.jdbc=jdbc:mysql://localhost:3306/permissionmdb?useUnicode=true[&];characterEncoding=utf8[&];serverTimezone=GMT%2B8

6、编写mybaits工具类

package com.han.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;

/**
 * @author Mr.Feng
 * @description:
 * @create 2022-08-01-11:17
 */
//构建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命令所需的所有方法
    //获取SqlSession连接
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
    //做两件事:加载资源、创建对象
    }

7、编写实体类

8、Dao接口

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

9、接口实现类由原来的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.han.dao.UserDao">
    <!--id对应方法名字-->
    <!--resultType返回一个结果 咱们这个查询语句执行会返回List<User>这个结果集-->
    <select id="getUserList" resultType="com.han.pojo.User">
    select * from user
  </select>
</mapper>

10、测试

可能出现问题说明:Maven静态资源过滤问题

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

test测试

package com.han.dao;

        import com.han.pojo.User;
        import com.han.utils.MybatisUtils;
        import org.apache.ibatis.session.SqlSession;
        import org.junit.Test;

        import java.util.List;

/**
 * @author Mr.Feng
 * @description:
 * @create 2022-08-01-14:12
 */
public class UserDaoTest {
    @Test
    public void test() {
        //第一步:获取SqlSession对象
        SqlSession sqlSession =MybatisUtils.getSession();
        try {

            //方式1:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }

            //方式2
//        List<User> userList = sqlSession.selectList("com.han.dao.UserDao.getUserList");
//        for (User user : userList) {
//            System.out.println(user);
//        }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭SQLSession
            sqlSession.close();
        }
    }
}

注意

  1. 将上面案例中的UserMapper接口改名为 UserDao;

  2. 将UserMapper.xml中的namespace改为为UserDao的路径 .

  3. 再次测试

配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!

select

  1. select标签是mybatis中最常用的标签之一
  2. select语句有很多属性可以详细配置每一条SQL语句
  3. SQL语句返回值类型。【完整的类名或者别名】
  4. 传入SQL语句的参数类型 。【万能的Map,可以多尝试使用】
  5. 命名空间中唯一的标识符
  6. 接口中的方法名与映射文件中的SQL语句ID 一一对应
  7. id 就是对应的 namespace中的方法名
  8. parameterType 参数类型
  9. resultType SQL语句执行的返回值
     

根据id查询用户

1、在UserMapper中添加对应方法

public interface UserDao {
    //查询全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
 }

2、在UserMapper.xml中添加Select语句

<?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.han.dao.UserDao">
    <!--id对应方法名字-->
    <!--resultType返回一个结果 咱们这个查询语句执行会返回List<User>这个结果集-->
    <select id="getUserList" resultType="com.han.pojo.User">
    select * from user
    </select>
    <select id="getUserById" resultType="com.han.pojo.User" parameterType="int">
    select * from user where id = #{id}
    </select>
</mapper>

3、测试类中测试

public class UserDaoTest {
    @Test
    public void test() {
        //第一步:获取SqlSession对象
        SqlSession sqlSession =MybatisUtils.getSession();
        try {

            //方式1:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }

            //方式2
//        List<User> userList = sqlSession.selectList("com.han.dao.UserDao.getUserList");
//        for (User user : userList) {
//            System.out.println(user);
//        }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭SQLSession
            sqlSession.close();
        }
    }
    @Test
    public void getUserById()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
}

insert

1、在UserMapper中添加对应方法

public interface UserDao {
    //查询全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //插入一个用户addUser
    int addUser(User user);
 }

2、在UserMapper.xml中添加Insert语句

<?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.han.dao.UserDao">
    <!--id对应方法名字-->
    <!--resultType返回一个结果 咱们这个查询语句执行会返回List<User>这个结果集-->
    <select id="getUserList" resultType="com.han.pojo.User">
    select * from user
    </select>
    <select id="getUserById" resultType="com.han.pojo.User" parameterType="int">
    select * from user where id = #{id}
    </select>
    <!--对象中的属性可以直接取出来-->
    <insert id="addUser" parameterType="com.han.pojo.User">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
</mapper>

3、测试类中测试

 //增删改需要提交事务,不能直接 mapper.addUser()插入成功
    @Test
    public void addUser()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int res = mapper.addUser(new User(4, "hahaha", "123"));
        if (res > 0){
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

update

1、在UserMapper中添加对应方法

public interface UserDao {
    //查询全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //插入一个用户addUser
    int addUser(User user);
    //修改用户
    int updateUser(User user);
 }

2、在UserMapper.xml中添加update语句

<?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.han.dao.UserDao">
    <!--id对应方法名字-->
    <!--resultType返回一个结果 咱们这个查询语句执行会返回List<User>这个结果集-->
    <select id="getUserList" resultType="com.han.pojo.User">
    select * from user
    </select>
    <select id="getUserById" resultType="com.han.pojo.User" parameterType="int">
    select * from user where id = #{id}
    </select>
    <!--对象中的属性可以直接取出来-->
    <insert id="addUser" parameterType="com.han.pojo.User">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="com.han.pojo.User">
        update user set name = #{name},pwd = #{pwd}  where id = #{id} ;
    </update>
</mapper>

3、测试类中测试

@Test
    public void updateUser()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int res = mapper.updateUser(new User(4, "hehehe", "123"));
        if (res > 0){
            System.out.println("更新成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

delete

1、在UserMapper中添加对应方法

public interface UserDao {
    //查询全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //插入一个用户addUser
    int addUser(User user);
    //修改用户
    int updateUser(User user);
    //删除一个用户
    int deleteUser(int id);
 }

2、在UserMapper.xml中添加delete语句

<?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.han.dao.UserDao">
    <!--id对应方法名字-->
    <!--resultType返回一个结果 咱们这个查询语句执行会返回List<User>这个结果集-->
    <select id="getUserList" resultType="com.han.pojo.User">
    select * from user
    </select>
    <select id="getUserById" resultType="com.han.pojo.User" parameterType="int">
    select * from user where id = #{id}
    </select>
    <!--对象中的属性可以直接取出来-->
    <insert id="addUser" parameterType="com.han.pojo.User">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="com.han.pojo.User">
        update user set name = #{name},pwd = #{pwd}  where id = #{id} ;
    </update>
    <!--参数类型是int的可以不用写-->
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
</mapper>

3、测试类中测试

public class UserDaoTest {
    @Test
    public void test() {
        //第一步:获取SqlSession对象
        SqlSession sqlSession =MybatisUtils.getSession();
        try {

            //方式1:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }

            //方式2
//        List<User> userList = sqlSession.selectList("com.han.dao.UserDao.getUserList");
//        for (User user : userList) {
//            System.out.println(user);
//        }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭SQLSession
            sqlSession.close();
        }
    }
    @Test
    public void getUserById()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
    //增删改需要提交事务,不能直接 mapper.addUser()插入成功
    @Test
    public void addUser()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int res = mapper.addUser(new User(4, "hahaha", "123"));
        if (res > 0){
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void updateUser()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int res = mapper.updateUser(new User(4, "hehehe", "123"));
        if (res > 0){
            System.out.println("更新成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteUser()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int res = mapper.deleteUser(4);
        /*不进行下面判断的话可以直接写mapper.deleteUser(4);然后直接提交事务即可*/
        if (res > 0){
            System.out.println("删除成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}

注意点:增删改需要提交事务!!!

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

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

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

多个参数用map或者注解

1.6 map的一些操作

select

1、在接口方法中,参数直接传递Map

User selectUserByNP2(Map<String,Object> map);

2、编写sql语句的时候,需要传递参数类型,参数类型为map

<select id="selectUserByNP2" parameterType="map" resultType="com.kuang.pojo.User">
  select * from user where name = #{username} and pwd = #{pwd}
</select>

3、在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!

Map<String, Object> map = new HashMap<String, Object>();
map.put("username","小明");
map.put("pwd","123456");
User user = mapper.selectUserByNP2(map);

总结:如果参数过多,我们可以考虑直接使用Map实现,如果参数比较少,直接传递参数即可

insert

1、在UserMapper接口中添加对应的方法

public interface UserDao {
   
    //万能Map
    int addUser2(Map<String,Object> map);
   
 }

2、编写sql语句的时候,需要传递参数类型,参数类型为map

<?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.han.dao.UserDao">
  
  
    <insert id="addUser2" parameterType="map">
        insert into user (id,name,pwd) values (#{userid},#{username},#{password});
    </insert>
   
</mapper>

3、在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求

 @Test
    public void addUser2()  {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        Map<String, Object> map = new HashMap<>();
        map.put("userid",8);
        map.put("username","fh");
        map.put("password","212112");
        int res = mapper.addUser2(map);
        if (res > 0) {
            System.out.println("增加成功");
        }

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}

注意:因为resultType一个是结果集的类型,parameterType一个是传入参数的类型

经过分析在查询中就只用到resultType,应该是查询的话就是得到整个对象的结果集

增删改的话要用到传入参数类型(要传参啊所以用parameterType)又delete只需要id,则parameterType="int",其他的都是 parameterType="com.han.pojo.User":

int addUser(User user);int updateUser(User user);int deleteUser(int id);

1.7 模糊查询

模糊查询like语句该怎么写?

第1种:在Java代码中添加sql通配符

//模糊查询
    List<User> getUserLike(String value);
  <select id="getUserLike" resultType="com.han.pojo.User">
        select * from user where name like #{value}
    </select>
@Test
    public void getUserLike() {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserLike("%李%");
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

 第2种:在sql语句中拼接通配符,会引起sql注入

string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
 
<select id=”selectlike”>
     select * from foo where bar like "%"#{value}"%"
</select>

根据 密码 和 名字 查询用户

思路一:直接在方法中传递参数

1、在接口方法的参数前加 @Param属性

2、Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型

//通过密码和名字查询用户
User selectUserByNP(@Param("username") String username,@Param("pwd") String pwd);
 
/*
    <select id="selectUserByNP" resultType="com.kuang.pojo.User">
      select * from user where name = #{username} and pwd = #{pwd}
    </select>
*/

小结:

所有的增删改操作都需要提交事务!

接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!

有时候根据业务的需求,可以考虑使用map传递参数!

为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!


1.8 配置解析

1、核心配置文件

  • mybatis-config.xml 系统核心配置文件

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

  • 能配置的内容如下:

configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
        environment(环境变量)
            transactionManager(事务管理器)
            dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
<!-- 注意元素节点的顺序!顺序不对会报错 -->

2、环境配置environments

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

配置MyBatis的多套运行环境,将SQL映射到多个不同的数据库上,必须指定其中一个为默认运行环境(通过default指定)

子元素节点:environmentdataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。

数据源是必须配置的。有三种内建的数据源类型

type="[UNPOOLED|POOLED|JNDI]")

unpooled:这个数据源的实现只是每次被请求时打开和关闭连接。

pooled:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来 , 这是一种使得并发 Web 应用快速响应请求的流行处理方式。

jndi:这个数据源的实现是为了能在如 Spring 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。

数据源也有很多第三方的实现,比如dbcp,c3p0,druid等等....

详情:点击查看官方文档

这两种事务管理器类型都不需要设置任何属性。

具体的一套环境,通过设置id进行区别,id保证唯一!

子元素节点:transactionManager - [ 事务管理器 ]

<!-- 语法 -->
<transactionManager type="[ JDBC | MANAGED ]"/>

子元素节点:数据源(dataSource)

MyBatis可以配置成多种环境版本

但是尽管客户以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境

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


3、属性(Properties) 

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

这些属性都是可外部配置且动态替换的,即可以在典型的Java属性文件中配置,也可通过Properties元素的子元素来传递【db.properties】

1、编写一个配置文件db.properties

driver = com.mysql.jdbc.Driver
name = jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8
username = root
password = 123456

2、在核心配置文件中引入

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

注意:properties标签要写上面

 注:

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

3、类型别名(typeAliases)优化

类型别名是为 Java 类型设置一个短的名字。

它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。

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


 <select id="getUserList" resultType="User">
    select * from user
 </select>

当这样配置时,User可以用在任何使用com.kuang.pojo.User的地方。

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

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

<select id="getUserList" resultType="user">
    select * from user
</select>

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

注意:在实体类比较少的情况下,使用第一种

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

           第一种可以DIY别名,第二种不行,但是如果非要改,需要在实体上增加注解,如:

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

4、设置

  • 设置(settings)相关 => 查看帮助文档

    • 懒加载

    • 日志实现

    • 缓存开启关闭

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

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

  1. 类型处理器
  2. 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。
  3. 你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。【了解即可】
  4. 对象工厂
  5. MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。
  6. 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过有参构造方法来实例化。
  7. 如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。【了解即可】
     

5、其他配置

  1. typeHandlers(类处理器)
  2. objectFactory(对象工厂)
  3. plugins插件:mybatis-generator-core、mybatis-plus、通用mapper
  • 设置(settings)相关 => 查看帮助文档

    • 懒加载

    • 日志实现

    • 缓存开启关闭

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

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

类型处理器

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。

你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。【了解即可】

对象工厂

MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。

默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过有参构造方法来实例化。

如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。【了解即可】

6、映射器(mappers)

映射器 : 定义映射SQL语句文件

既然 MyBatis 的行为其他元素已经配置完了,我们现在就要定义 SQL 映射语句了。但是首先我们需要告诉 MyBatis 到哪里去找到这些语句。Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的 URL),或类名和包名等。映射器是MyBatis中最核心的组件之一,在MyBatis 3之前,只支持xml映射器,即:所有的SQL语句都必须在xml文件中配置。而从MyBatis 3开始,还支持接口映射器,这种映射器方式允许以Java代码的方式注解定义SQL语句,非常简洁。

方式一:【推荐使用】

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

 方式二:使用class文件绑定注册,使用与注解开发

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

注意点:

        接口和他的Mapper配置文件必须同名!

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

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

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

注意点:

        接口和他的Mapper配置文件必须同名!

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

方式四:

<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>

7、生命周期和作用域

作用域理解

  1. SqlSessionFactoryBuilder 的作用在于创建 SqlSessionFactory,创建成功后,SqlSessionFactoryBuilder 就失去了作用,所以它只能存在于创建 SqlSessionFactory 的方法中,而不要让其长期存在。因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。
  2. SqlSessionFactory 可以被认为是一个数据库连接池,它的作用是创建 SqlSession 接口对象。因为 MyBatis 的本质就是 Java 对数据库的操作,所以 SqlSessionFactory 的生命周期存在于整个 MyBatis 的应用之中,所以一旦创建了 SqlSessionFactory,就要长期保存它,直至不再使用 MyBatis 应用,所以可以认为 SqlSessionFactory 的生命周期就等同于 MyBatis 的应用周期。
  3. 由于 SqlSessionFactory 是一个对数据库的连接池,所以它占据着数据库的连接资源。如果创建多个 SqlSessionFactory,那么就存在多个数据库连接池,这样不利于对数据库资源的控制,也会导致数据库连接资源被消耗光,出现系统宕机等情况,所以尽量避免发生这样的情况。
  4. 因此在一般的应用中我们往往希望 SqlSessionFactory 作为一个单例,让它在应用中被共享。所以说 SqlSessionFactory 的最佳作用域是应用作用域。
  5. 如果说 SqlSessionFactory 相当于数据库连接池,那么 SqlSession 就相当于一个数据库连接(Connection 对象),你可以在一个事务里面执行多条 SQL,然后通过它的 commit、rollback 等方法,提交或者回滚事务。所以它应该存活在一个业务请求中,处理完整个请求后,应该关闭这条连接,让它归还给 SqlSessionFactory,否则数据库资源就很快被耗费精光,系统就会瘫痪,所以用 try...catch...finally... 语句来保证其正确关闭。
  6. 所以 SqlSession 的最佳的作用域是请求或方法作用域。
     

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

问题

 测试出现问题

 解决方法

  1. 起别名
 <select id="getUserById" resultType="com.han.pojo.User">
    select id,name,pwd as password from user where id = #{id}
 </select>
  1. 结果集映射->ResultMap【推荐】
<!--结果集映射-->
<resultMap id="UserMap" type="User">
    <!-- id为主键 -->
    <id column="id" property="id"/>
    <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
 
<select id="selectUserById" resultMap="UserMap">
    select id , name , pwd from user where id = #{id}
</select>

自动映射

  1. resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来。
  2. 实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的长达数千行的代码。
  3. ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
  4. 你已经见过简单映射语句的示例了,但并没有显式指定 resultMap。比如:
    <select id="selectUserById" resultType="map">
    select id , name , pwd
        from user
        where id = #{id}
    </select>

    上述语句只是简单地将所有的列映射到 HashMap 的键上,这由 resultType 属性指定。虽然在大部分情况下都够用,但是 HashMap 不是一个很好的模型。你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为模型。

    ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们

    9、日志

日志工厂

思考:我们在测试SQL的时候,要是能够在控制台输出 SQL 的话,是不是就能够有更快的排错效率?

如果一个 数据库相关的操作出现了问题,我们可以根据输出的SQL语句快速排查问题。

对于以往的开发过程,我们会经常使用到debug模式来调节,跟踪我们的代码执行过程。但是现在使用Mybatis是基于接口,配置文件的源代码执行过程。因此,我们必须选择日志工具来作为我们开发,调节程序的工具。

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种工具:

SLF4J

Apache Commons Logging

Log4j 2

Log4j

JDK logging

具体选择哪个日志实现工具由MyBatis的内置日志工厂确定。它会使用最先找到的(按上文列举的顺序查找)。如果一个都未找到,日志功能就会被禁用。

 标准日志实现

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

在mybatis核心配置文件中 输出我们的日志

Log4j

简介:

  1. Log4j是Apache的一个开源项目
  2. 通过使用Log4j,我们可以控制日志信息输送的目的地:控制台,文本,GUI组件....
  3. 我们也可以控制每一条日志的输出格式;
  4. 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
     

使用步骤:

1、导入log4j的包

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

2、配置文件编写

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
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/kuang.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、setting设置日志实现

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

4、在程序中使用Log4j进行输出!

//注意导包:org.apache.log4j.Logger
static Logger logger = Logger.getLogger(MyTest.class);
 
@Test
public void selectUser() {
    logger.info("info:进入selectUser方法");
    logger.debug("debug:进入selectUser方法");
    logger.error("error: 进入selectUser方法");
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    List<User> users = mapper.selectUser();
    for (User user: users){
        System.out.println(user);
    }
    session.close();
}

5、测试,看控制台输出!

  • 使用Log4j 输出日志

  • 可以看到还生成了一个日志的文件 【需要修改file的日志级别】

10、分页

思考:为什么需要分页?

在学习mybatis等持久层框架的时候,会经常对数据进行增删改查操作,使用最多的是对数据库进行查询操作,如果查询大量数据的时候,我们往往使用分页进行查询,也就是每次处理小部分数据,这样对数据库压力就在可控范围内。

使用Limit实现分页

#语法
SELECT * FROM table LIMIT stratIndex,pageSize
 
SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15  
 
#为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:   
SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.  
 
#如果只给定一个参数,它表示返回最大的记录行数目:   
SELECT * FROM table LIMIT 5; //检索前 5 个记录行  
 
#换句话说,LIMIT n 等价于 LIMIT 0,n。 

步骤

1、Mapper接口,参数为map

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

2、修改Mapper文件

 <resultMap id="UserMap" type="User">
        <!--column数据库中的字段,property实体类中的属性-->
       <!-- <result column="id" property="id"></result>
        <result column="name" property="name"></result>-->
        <result column="pwd" property="password"></result>
    </resultMap>

  
    <!--分页查询实现-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
    select * from user limit #{startIndex},#{pageSize}
    </select>


//没有resultMap的话 单写就是
  <!--分页查询实现-->
    <select id="getUserByLimit" parameterType="map" resultType="user">
    select * from user limit #{startIndex},#{pageSize}
    </select>

3、在测试类中传入参数测试

  • 推断:起始位置 =  (当前页面 - 1 ) * 页面大小

//分页查询 , 两个参数startIndex , pageSize
@Test
public void testSelectUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
 
    int currentPage = 1;  //第几页
    int pageSize = 2;  //每页显示几个
    Map<String,Integer> map = new HashMap<String,Integer>();
    map.put("startIndex",(currentPage-1)*pageSize);
    map.put("pageSize",pageSize);
 
    List<User> users = mapper.selectUser(map);
 
    for (User user: users){
        System.out.println(user);
    }
 
    session.close();
}
  @Test
    public void getUserByLimit() {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String,Integer> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userList = mapper.getUserByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

RowBounds分页

1、mapper接口

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

2、mapper文件


    <select id="getUserByRowBounds" resultMap="UserMap">
     select * from user
    </select>

3、测试类

在这里,我们需要使用RowBounds类

@Test
public void testUserByRowBounds() {
    SqlSession session = MybatisUtils.getSession();
 
    int currentPage = 2;  //第几页
    int pageSize = 2;  //每页显示几个
    RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize);
 
    //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了]
    List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserByRowBounds", null, rowBounds);
 
    for (User user: users){
        System.out.println(user);
    }
    session.close();
}
@Test
public void testUserByRowBounds() {
    SqlSession session = MybatisUtils.getSession();
 
    int currentPage = 2;  //第几页
    int pageSize = 2;  //每页显示几个
    RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize);
 
    //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了]
    List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserByRowBounds", null, rowBounds);
 
    for (User user: users){
        System.out.println(user);
    }
    session.close();
}

PageHelper插件

 11、注解

面向接口编程

  1. 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
  2. 根本原因 :  解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
  3. 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
  4. 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
  5. 关于接口的理解
  6. 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
  7. 接口的本身反映了系统设计人员对系统的抽象理解。
  8. 接口应有两类:
  9. 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
  10. 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
  11. 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
  12. 三个面向区别:
  13. 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法 .
  14. 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现 .
  15. 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构

    mybatis最初配置信息是基于 XML ,映射语句(SQL)也是定义在 XML 中的。而到MyBatis 3提供了新的基于注解的配置。不幸的是,Java 注解的的表达力和灵活性十分有限。最强大的 MyBatis 映射并不能用注解来构建

    sql 类型主要分成 :

    @select ()

    @update ()

    @Insert ()

    @delete ()

    注意:利用注解开发就不需要mapper.xml映射文件了 .

    1、我们在我们的接口中添加注解

//查询全部用户
@Select("select id,name,pwd password from user")
public List<User> getAllUser();

2、在mybatis的核心配置文件中注入

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

3、我们去进行测试

@Test
public void testGetAllUser() {
    SqlSession session = MybatisUtils.getSession();
    //本质上利用了jvm的动态代理机制
    UserMapper mapper = session.getMapper(UserMapper.class);
 
    List<User> users = mapper.getAllUser();
    for (User user : users){
        System.out.println(user);
    }
 
    session.close();
}

4、利用Debug查看本质

 5、本质上利用了jvm的动态代理机制

 6、Mybatis详细的执行流程


注解增删改 要提交事务

1、在工具类创建的时候实现自动事务提交

  public static SqlSession getSession() {
        return sqlSessionFactory.openSession(true);
    }

2、编写接口,增加注解

public interface UserMapper {
    @Select("select * from user")
    public List<User> getUsers();

    //若方法存在多个参数,所有的参数面前必须加上@Param("id")注解
    @Select("select * from user where id = #{id}")
    User getUserByID(@Param("id") int id);
    @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
    int addUser(User user);
    /*不用提交事务了 因为在工具类中 默认事务提交设为true
    *  public static SqlSession getSession() {
        return sqlSessionFactory.openSession(true);
    }
    * */
    @Update("update user set name=#{name},pwd=#{password} where id = #{id}")
    int updateUser(User user);
    @Delete("delete from user where id = #{id}")
    //基本类型参数用@Param
    int deleteUserID(@Param("id") int id);
}

3、测试类

public class UserMapperTest {
    @Test
    public void test() {
        SqlSession session = MybatisUtils.getSession();
        //本质上利用了jvm的动态代理机制
        UserMapper mapper = session.getMapper(UserMapper.class);

        List<User> users = mapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
        session.close();
    }

    @Test
    public void test1() {
        SqlSession session = MybatisUtils.getSession();
        //本质上利用了jvm的动态代理机制
        UserMapper mapper = session.getMapper(UserMapper.class);

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

    @Test
    public void test2() {
        SqlSession session = MybatisUtils.getSession();
        //本质上利用了jvm的动态代理机制
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.addUser(new User(10,"fhh","11111"));
        session.close();
    }
    @Test
    public void test3() {
        SqlSession session = MybatisUtils.getSession();
        //本质上利用了jvm的动态代理机制
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.updateUser(new User(10,"haha","1"));
        session.close();
    }

    @Test
    public void test4() {
        SqlSession session = MybatisUtils.getSession();
        //本质上利用了jvm的动态代理机制
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.deleteUserID(5);
        session.close();
    }
}

【注意:我们必须要将接口注册绑定我们的核心配置文件中】

 【注意点:增删改一定记得对事务的处理】

关于@Param

@Param注解用于给方法参数起一个名字。以下是总结的使用原则:

在方法只接受一个参数的情况下,可以不使用@Param。

在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。

如果参数是 JavaBean , 则不能使用@Param。

不使用@Param注解时,参数只能有一个,并且是Javabean。

#与$的区别

#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? 【推荐使用】

INSERT INTO user (name) VALUES (#{name});
INSERT INTO user (name) VALUES (?);

${} 的作用是直接进行字符串替换:用$不安全不能防止SQL注入问题

INSERT INTO user (name) VALUES ('${name}');
INSERT INTO user (name) VALUES ('kuangshen');

使用注解和配置文件协同开发,才是MyBatis的最佳实践!


Lombok 

 

 12、多对一的处理

多对一的理解:

  • 多个学生对应一个老师

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

数据库设计

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
 
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');
 
CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
 
 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

测试环境搭建

1、导入lomback

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
</dependency>

2、新建实体类Student、Teacher

@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 TeacherMapper {

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

4、建立mapper.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.han.dao.TeacherMapper">


</mapper>

5、在核心配置文件中绑定注册我们的Mapper文件接口或文件【方式很多,随心选】

<mappers>
    <!--注解要用class不能用resource-->
    <mapper class="com.han.dao.TeacherMapper"></mapper>
    <mapper class="com.han.dao.StudentMapper"></mapper>
</mappers>

6、测试能否查询成功

public class MytTest01 {
    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtils.getSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);

        sqlSession.close();
    }
}

【注意】resources下建多级目录用 / 分割的大哥


搭建测试环境

1、IDEA安装Lombok插件

2、引入Maven依赖

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.10</version>
</dependency>

3、在代码中增加注解

@Data //GET,SET,ToString,有参,无参构造
public class Teacher {
    private int id;
    private String name;
}
@Data
public class Student {
    private int id;
    private String name;
    //多个学生可以是同一个老师,即多对一
    private Teacher teacher;
}

、编写实体类对应的Mapper接口 【两个】

  • 无论有没有需求,都应该写上,以备后来之需!

public interface StudentMapper {
}

public interface TeacherMapper {
}

、编写Mapper接口对应的 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、TeacherMapper接口增加方法

//获取所有学生及对应老师的信息
public List<Student> getStudents();

2、编写对应的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.StudentMapper">
 
    <!--
    需求:获取所有学生及对应老师的信息
    思路:
        1. 获取所有学生的信息
        2. 根据获取的学生信息的老师ID->获取该老师的信息
        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>
 
</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.han.dao.StudentMapper">
    <!--思路:
            1.查询所有的学生信息
            2.根据查询出来的学生的tid,寻找对应的老师,相当于子查询
    -->
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student;
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"></result>
        <result property="name" column="name"></result>
        <!--复杂的属性,我们需要单独处理 对象:association 集合:collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
    </resultMap>
    <select id="getTeacher" resultType="teacher">
        select * from teacher where id = #{id}
    </select>



</mapper>

3、编写完毕去Mybatis配置文件中,注册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 testGetStudents(){
    SqlSession session = MybatisUtils.getSession();
    StudentMapper mapper = session.getMapper(StudentMapper.class);
 
    List<Student> students = mapper.getStudents();
 
    for (Student student : students){
        System.out.println(
                "学生名:"+ student.getName()
                        +"\t老师:"+student.getTeacher().getName());
    }
}
public class MytTest01 {
    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtils.getSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudent();
        for (Student student : studentList) {
            System.out.println(student);
        }

        sqlSession.close();
    }
}

按照结果嵌套处理

#{id}里的id可以写任何值,会自动认为是 column="tid" 中的tid

 查询是一条一条执行的,当执行到tid时候去调用映射,映射又去子查询,所以#{}里面自动填充了column的值,所以#{ }里面随意填写

id=0的前面select加上t.id tid,association里加<result property="id" column="tid"/> 就好了

出查询的结果是id=0的是因为在sql里面没有输出老师的id,你自己输出一下,在映射里面在映射一下就行了


整体步骤

1、给StudentMapper接口增加方法

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

2、编写对应的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.han.dao.StudentMapper">

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





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



</mapper>
<!--
按查询结果嵌套处理
思路:
    1. 直接查询出结果,进行结果集的映射
-->
<select id="getStudents2" 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="StudentTeacher2" 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、去mybatis-config文件中注入【此处应该处理过了】

4、测试

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

        sqlSession.close();
    }
@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中的联表查询

13、一对多的处理

一对多处理

一对多的理解:

  • 一个老师拥有多个学生

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

实体类编写

@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 interface TeacherMapper {
    //获取老师
    List<Teacher> getTeacher();
    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher1(@Param("tid") int id);
    Teacher getTeacher2(@Param("tid") int id);

}

2、编写接口对应的Mapper配置文件

<mapper namespace="com.kuang.mapper.TeacherMapper">
 
    <!--
    思路:
        1. 从学生表和老师表中查出学生id,学生姓名,老师姓名
        2. 对查询出来的操作做结果集映射
            1. 集合的话,使用collection!
                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>
<?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.han.dao.TeacherMapper">
    <select id="getTeacher" resultType="Teacher">
        select * from teacher;
    </select>
    <!--按照结果嵌套查询-->
    <select id="getTeacher1" 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>
    <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>

</mapper>

3、将Mapper文件注册到MyBatis-config文件中

<mappers>
    <mapper resource="mapper/TeacherMapper.xml"/>
</mappers>

<mappers>
    <!--注解要用class不能用resource-->
    <mapper class="com.han.dao.TeacherMapper"></mapper>
    <mapper class="com.han.dao.StudentMapper"></mapper>
</mappers>

4、测试

public class MyTest {
    @Test
    public void test021() {
        SqlSession sqlSession = MybatisUtils.getSession();
        for (Teacher teacher : sqlSession.getMapper(TeacherMapper.class).getTeacher()){
            System.out.println(teacher);
        }
    }

    @Test
    public void test2() {
        SqlSession sqlSession = MybatisUtils.getSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper.getTeacher1(1);
        System.out.println(teacher1);
        sqlSession.close();
    }
    @Test
    public void test3() {
        SqlSession sqlSession = MybatisUtils.getSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper.getTeacher2(1);
        System.out.println(teacher1);
        sqlSession.close();
    }

}

本质上就是将sql查询出来的各个字段,封装到POJO的属性中去。

按查询嵌套处理

1、TeacherMapper接口编写方法

public Teacher getTeacher2(int id);

public interface TeacherMapper {
    //获取老师
    List<Teacher> getTeacher();
    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher1(@Param("tid") int id);
    Teacher getTeacher2(@Param("tid") 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>
<?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.han.dao.TeacherMapper">

    <!--=======================================================================-->
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from  teacher where id = #{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <!--javaType java类型是个集合,ofType泛型时student-->
        <!--本质还是一个老师,但是和上面的select*一致可以省略,就第三个老师里面的student不一样,要做映射-->
       <!-- <result property="id" column="id"/>
        <result property="name" column="name"/>-->
        <!--老师的id[ column="id"]返回过来 学生要查 把id丢给你-->
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
    </resultMap>
    <!--通过老师的id获取下面的所有学生-->
   <!-- 这个id[#{tid} ] 随便写-->
    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid = #{tid}
    </select>

</mapper>

3、将Mapper文件注册到MyBatis-config文件中

4、测试

public class MyTest {
    @Test
    public void test021() {
        SqlSession sqlSession = MybatisUtils.getSession();
        for (Teacher teacher : sqlSession.getMapper(TeacherMapper.class).getTeacher()){
            System.out.println(teacher);
        }
    }

    @Test
    public void test2() {
        SqlSession sqlSession = MybatisUtils.getSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper.getTeacher1(1);
        System.out.println(teacher1);
        sqlSession.close();
    }
    @Test
    public void test3() {
        SqlSession sqlSession = MybatisUtils.getSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper.getTeacher2(1);
        System.out.println(teacher1);
        sqlSession.close();
    }

}

小结

1、关联-association

2、集合-collection

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

4、JavaType和ofType都是用来指定对象类型的

JavaType是用来指定pojo中属性的类型

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

注意说明:

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

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

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

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

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

一对多和多对一对于很多人来说是难点,一定要大量的做练习理解!


14、动态SQL

介绍

什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.

官网描述:
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
 
    -------------------------------
    - if
    - choose (when, otherwise)
    - trim (where, set)
    - foreach
    -------------------------------

我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。

那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。

搭建环境

新建一个数据库表:blog

字段:id,title,author,create_time,views
 

CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT '博客id',
  `title` varchar(100) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建一个基础工程

1、导包

2、编写配置文件

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>

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

    </properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--可以给实体类起别名-->
   <!-- <typeAliases>
        <typeAlias type="com.han.pojo.User" alias="User"></typeAlias>
    </typeAliases>-->

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

    <!--default=“”可选,即可以写多个<environments></environments>-->
    <environments default="development">

        <environment id="development">
            <!--事务管理-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <!--&amp;转义字符,相当无and-->
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>

        <environment id="test">
            <!--事务管理-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--&amp;转义字符,相当无and-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<mappers>
    <!--注解要用class不能用resource-->
    <mapper class="com.han.dao.TeacherMapper"></mapper>
    <mapper class="com.han.dao.StudentMapper"></mapper>
</mappers>

</configuration>

db.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username = root
password = 123456

3、编写实体类

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

4、编写实体类对应Mapper接口和Mapper.xm文件

public interface BlogMapper {
    //插入数据
    int addBlog(Blog blog);
}
<?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.han.dao.BlogMapper">

    <!--扫描实体类的包,他的默认别名就位在这个类的类名首字母小写-->
    <insert id="addBlog" parameterType="blog">
    insert into blog (id, title, author, create_time, views)
    values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
</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、插入初始数据

编写工具类IDutils工具类

@SuppressWarnings("all")//抑制警告
public class IDutils {//获得一个随机id
    public static  String genId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
    @Test
    public void test(){
        System.out.println(IDutils.genId());
        System.out.println(IDutils.genId());
        System.out.println(IDutils.genId());
    }

}

编写工具类MybatisUtils工具类

//构建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命令所需的所有方法
    //获取SqlSession连接
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession(true);
    }
    //做两件事:加载资源、创建对象
    }

初始化博客方法

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

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

        mapper.addBlog(blog);

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

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

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

        session.close();
    }

设置了还是报错的记得看下mapper里的insert语句,注意第一行into后的的是create_time,第二行values后的才是createTime!!!还有改配置文件后别忘记刷新maven


IF语句

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

1、编写接口类

public interface BlogMapper {
    List<Blog> queryBlogIF(Map map);
}

2、编写SQL语句

<?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.han.dao.BlogMapper">

    <!-- List<Blog> queryBlogIF(Map map); 这边返回结果是Blog 要返回结果blog-->
    <select id="queryBlogIF" 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>

<!--需求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>
</select>

3、测试

  @Test
    public void queryBlogIF(){
        SqlSession sqlSession = MybatisUtils.getSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        //map.put("title","Java如此简单");
        map.put("author","狂神说");
        List<Blog> blogs = mapper.queryBlogIF(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();

    }

这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!

Where

修改上面的SQL语句;

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

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

Set

同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 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语句(if 是拼接,choose是选择) 

choose(when,otherwise)

只会选择其中的一个去实现

public interface BlogMapper {
    List<Blog> queryBlogChoose(Map map);
}
<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                and author = #{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
    </where>

</select>

 @Test
    public void queryBlogChoose(){
        SqlSession sqlSession = MybatisUtils.getSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
//        map.put("title","Java如此简单");
        map.put("author","狂神说");
        map.put("views","9999");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

trim(where、set)

<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>
#注 把where 1=1去掉 用where标签代替,拼接动态sql更加智能

没提交事务也能成功是因为在MybatisUtils类里的getSession方法里开启了自动提交事务

1、BlogMapper和BlogMapper.xml

public interface BlogMapper {
    
    int updateBlog(Map map);
}
 <!--增删改 没有resultType 默认就是int
    mybaits增删改都不需要resultType,会有一个默认返回的-->
    <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>

2、测试

 


 Foreach

 and 后面不加空格会报错!!

and(之间要有空格,不知道为什么

 

将数据库中前三个数据的id修改为1,2,3;

需求:我们需要查询 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 where 1=1 and (id=1 or id=2 or id=3)
      -->
        <foreach collection="ids"  item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>
 <!--select * from blog where 1=1 and (id=1 or id =2 or id =3 )
        动态SQL与where标签可以省略where 1 = 1
        我们现在传递一个万能的map,这map中可以存在一个集合-->
    <select id="selectBlogForeach" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <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 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧。

动态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>

引用SQL片段:

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

注意:

①、最好基于 单表来定义 sql 片段,提高片段的可重用性,SQL片段不要做太复杂是查询,如多表连接

②、在 sql 片段中不要包括 wher

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

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


15、缓存

简介

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

一次查询的结果,给他暂存到一个可以取到得地方 --->内存: 缓存

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

1、什么是缓存 [ Cache ]?

存在内存中的临时数据。

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

2、为什么使用缓存?

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

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

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


主从复制是指现在主节点修改数据然后传递到从节点上修改

Mybatis缓存

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

一级缓存

一级缓存也叫本地缓存:

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中。

  • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库

测试

  1. 开启日志
  2. 测试在一个Session中查询两次相同记录
  3. 查看日志输出
public interface UserMapper {
    //根据id查询用户
    User queryUserById(@Param("id")int id);
}
<mapper namespace="com.han.dao.UserMapper">

    <!--parameterType="_int" 基本类型参数可以省略-->
    <select id="queryUserById" resultType="user">
        select * from user where id = #{id}
    </select>

</mapper>
@Test
    public void test1() {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        System.out.println("==================");
        User user2 = mapper.queryUserById(1);
        System.out.println(user2);
        System.out.println(user == user2);
        sqlSession.close();
    }

一级缓存失效的四种情况

一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;

一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

1、sqlSession相同,查询条件不同

观察结果:发现发送了两条SQL语句!很正常的理解

结论:当前缓存中,不存在这个数据

2、sqlSession相同,两次查询之间执行了增删改操作!

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

增加方法

ublic interface UserMapper {
   
    int updateUser(User user);
}

编写SQL

 <update id="updateUser" parameterType="user">
        update user set name = #{name},pwd = #{pwd} where id = #{id}
    </update>

测试

  @Test
    public void test1() {
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        mapper.updateUser(new User(2,"fh","hahaha"));
        System.out.println("==================");
        User user2 = mapper.queryUserById(1);
        System.out.println(user2);
        System.out.println(user == user2);
        sqlSession.close();
    }

 3、查询不同的Mapper.xml(不同的mapper连二级缓存都不在,别说一级)

一级缓存就是在代码之间,开启和关闭之间

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();
}

5、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();
}

观察结果:发现发送了两条SQL语句!

结论:每个sqlSession中的缓存相互独立


小结:一级缓存默认是开启的,只在一次sqlsession中有效,

也就是拿到连接到关闭连接这个区间段

一级缓存就是一个map


二级缓存

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

使用步骤

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

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

2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】

<cache/>
 
官方示例=====>查看官方文档
<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

代码测试

  • 所有的实体类先实现序列化接口

  • 测试代码

@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();
}

结论

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

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

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

 缓存原理

 数据库是老师,一级缓存是班长,二级缓存是小组长,有事不都是先找小组长嘛。

二级缓存是在一级缓存关闭时保存一级缓存的缓存数据,二级没有有两个可能,一个可能是session没关闭,缓存在一级,另一个可能是一级缓存也没有,需要从数据库查询

回答前面的,不一定,可能sqlsession还未关闭,还没有提交到二级缓存,所以存在二级缓存没有,而一级缓存有的情况

 自定义缓存-EhCache

Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;

要在应用程序中使用Ehcache,需要引入依赖的jar包

<!-- 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.xml中使用对应的缓存即可

<mapper namespace = “org.acme.FooMapper” > 
    <cache type = “org.mybatis.caches.ehcache.EhcacheCache” /> 
</mapper>

编写ehcache.xml文件,如果在加载时未找到/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:是否保存到磁盘,当系统当机时
      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>

合理的使用缓存,可以让我们程序的性能大大提升!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值