SSM框架学习日志——Mybatis详述

Mybatis

1、简介

1.1 什么是Mybatis

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

如何获得Mybatis

  • Maven仓库
  • Github
  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.2 持久化

数据持久化

  • 持久化就是将程序的数据在持久化和瞬时状态转化的过程
  • 内存:断电即失
  • 数据库(JDBC),io文件持久化

1.3 持久层

Dao层,Service层,Controller层

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

1.4 为什么需要Mybatis

  • 方便
  • 传统的JDBC代码太复杂了。简化、框架
  • 将数据存入到数据库中

2、第一个Mybatis程序

2.1 搭建环境

搭建数据库

CREATE DATABASE `mybatis`;

USE `mybatis`;

CREATE TABLE `user`(
id INT(`user`10) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) NOT NULL,
pwd VARCHAR(20) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

DELETE FROM `user` WHERE `id`=1;

INSERT INTO `user``user``user`(id,`name`,pwd) VALUES
(1,'张小敬',1234),
(2,'张三','1234'),
(3,'李四','1234');

新建Maven项目,导入依赖

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

2.2 创建一个模块

  1. 配置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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="1234"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
  2. 编写mybatis工具类

    package com.xiaojing.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    public class MybatisUtils {
        static {
            try {
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //sqlsession完全包含了CRUD
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

2.3 编写代码

  • 编写实体类

    package com.xiaojing.pojo;
    
    public class User {
        private int id;
        private String name;
        private String 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接口

    public interface UserDao {
        List<User> getUser();
    }
    
  • 编写UserMapper.xml文件绑定接口和执行sql语句

    <?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是接口类-->
    <mapper namespace="com.xiaojing.dao.UserDao">
        <!--查询语句-->
        <!--    id是接口名-->
        <select id="getUser" resultType="com.xiaojing.pojo.User">
            select * from mybatis.user ;
        </select>
    </mapper>
    

2.4 测试

public class UserDaoTest {
    @Test
    public void Test() throws IOException {
        SqlSession session = null;
        try{
            session = MybatisUtils.getSqlSession();
            UserDao mapper = session.getMapper(UserDao.class);
            List<User> userList = mapper.getUser();
            for (User user : userList) {
                System.out.println(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
    }
}

在测试的时候,遇到了各种bug:

  • 首先是 2 字节的 UTF-8 序列的字节 2 无效问题
    • 完全搞不懂这个问题的原因,百度多条发现是在xml文件中中文注释的问题,将xml文件的中文注释删除,解决
    • 后续发现,将xml的encoding=UTF-8改为encoding=UTF8可以解决问题
  • 第二个是java.lang.ExceptionInInitializerError
    • 这个异常是调用了未初始化的静态变量导致的,因为静态代码块或者静态变量在初始化的时候是按声明的顺序初始化的,而调用未初始化的静态变量就会导致该异常
  • 最后一个问题才是最糟心的:数据库连接问题!
    • 设置setTimeZone=UTC,没有解决
    • 设置set-on-borrow=true,没有解决
    • 重启mysql,没有解决
    • 最后发现,我的mysql版本是8.0.20,而Maven导入的依赖包mysql-connector-java却是8.0.11的,没想到这细微的版本差异会导致错误,真是令人吐血!

3、CRUD

3.1 参数描述

  • namespace:完整的接口包名

  • id:接口方法名

  • parameterType:参数类型

  • resultType:完整的返回值类型

3.2 步骤

  1. 写接口

    package com.xiaojing.dao;
    
    import com.xiaojing.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
        //查询所有用户
        List<User> getUser();
        //根据id查询用户
        User getUserById(int id);
        //增加用户
        int addUser(User user);
        //更改用户
        int updateUser(User user);
        //删除用户
        int deleteUser(int id);
    }
    
  2. 在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">
    
    <mapper namespace="com.xiaojing.dao.UserMapper">
        <!--select-->
        <select id="getUser" resultType="com.xiaojing.pojo.User">
            select *from mybatis.user
        </select>
    
        <select id="getUserById" parameterType="int" resultType="com.xiaojing.pojo.User">
            select * from mybatis.user where id=#{id}
        </select>
    
        <!--insert-->
        <insert id="addUser" parameterType="com.xiaojing.pojo.User">
            insert into mybatis.user(id,`name`,pwd) values (#{id},#{name},#{pwd})
        </insert>
    
        <!--update-->
        <update id="updateUser" parameterType="com.xiaojing.pojo.User">
            update mybatis.user set `name`=#{name},pwd=#{pwd} where id=#{id}
        </update>
    
        <!--delete-->
        <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id=#{id}
        </delete>
    </mapper>
    
  3. 测试

    package com.xioajing.dao;
    
    import com.xiaojing.dao.UserMapper;
    import com.xiaojing.pojo.User;
    import com.xiaojing.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.util.List;
    
    public class UserMapperTest {
        //查
        @Test
        public void getUserByIdTest(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserById(1);
            System.out.println(user);
            sqlSession.close();
        }
        //增
        @Test
        public void addUserTest(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.addUser(new User(4, "老赵", "1234"));
            //必须提交事务
            if(i > 0){
                sqlSession.commit();
            }
            sqlSession.close();
        }
        //改
        @Test
        public void updateUserTest(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.updateUser(new User(4,"赵老","1234"));
            sqlSession.commit();
            sqlSession.close();
        }
        //删
        @Test
        public void deleteUserTest(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.deleteUser(4);
            sqlSession.commit();
            sqlSession.close();
        }
    }
    

注意:增删改操作完之后,一定记住要提交事务!

当表中的字段增多,CRUD操作变得复杂,可以用map来减少不必要的传参!

3.3 思考

模糊查询怎么做?

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

        //模糊查询
        @Test
        public void getUserLikeTest(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserLike("%张%");
            for (User user : userList) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    
  2. 方法二:在sql语句拼接的时候写死

        <select id="getUserLike" resultType="com.xiaojing.pojo.User">
            select * from user where name like "%"#{value}"%";
        </select>
    

    为了安全建议使用方法二,更加安全

4、配置解析

4.1 核心配置文件

  • mybatis-config.xml

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

4.2 环境配置(environments)

MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中,不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境,每个数据库对应一个 SqlSessionFactory 实例。

Mybatis默认的事务管理器是JDBC,默认的数据源(Datasource)是POOLED(有池的)

4.3 属性(properties)

这些属性可以在外部进行配置,并可以进行动态替换.

  1. 编写配置文件,比如db.properties

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
    username=root
    password=1234
    
  2. 在mybatis-config.xml加载配置

     <properties resource="db.properties">
         <property name="username" value="root"/>
         <property name="password" value="1111"/>
     </properties>
    

    注意:properties属性需要放在configuration的首位,且外部配置文件的优先级比内部配置要高,如果外部配置和内部配置有相同的字段,优先使用外部配置文件的字段

4.4 类型别名(typeAliases)

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

第一种方式:

    <typeAliases>
        <typeAlias type="com.xiaojing.pojo.User" alias="User"/>
    </typeAliases>

第二种方式:

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

当实体类不是很多的时候,建议用第一种方式;否则,用第二种

第一种方式可以DIY别名;第二种没法,一般默认使用Java Bean 的首字母小写的非限定类名来作为它的别名,如果非要DIY,可以在实体类上加个注解

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

4.5 设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为,举两个重要的设置:

4.6 映射器(mappers)

自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件

第一种方式:相对类路径进行映射

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

第二种方式:使用映射器接口实现类的完全限定类名

<mappers >
    <mapper class="com.xiaojing.dao.UserMapper"/>
</mappers>
注意:接口和它的Mapper文件必须同名,且在同一个包下

第三种方式:将包内的映射器接口实现全部注册为映射器

<mappers >
    <package name="com.xiaojing.dao"/>
</mappers>
注意:接口和它的Mapper文件必须同名,且在同一个包下

4.7 作用域(Scope)和生命周期

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

SqlSessionFactoryBuilder
  • 一旦创建了 SqlSessionFactory,就不再需要它了
  • 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)
SqlSessionFactory
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。

  • 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。

  • 因此 SqlSessionFactory 的最佳作用域是应用作用域,即全局变量

  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession
  • 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域(局部变量)。
  • 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。
  • 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。
  • 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。
  • 一个SqlSession 相当于对“数据池”的一次请求,需要开启和关闭,否则就会浪费资源。

5、解决实体类属性名和数据库字段名不匹配的问题

5.1 问题

public class User {
    private int id;
    private String name;
    private String password;//此处属性名与数据库字段名不一致

测试结果:

原因在于:

select * from mybatis.user where id=#{id} 相当于 select id,`name`,pwd from mybatis.user where id=#{id}
而pwd不在实体类User的属性中

5.2 resultmap(结果集映射)

数据库:id name pwd

实体类:id name password

<!--结果集映射-->
<resultMap id="Usermap" type="User">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
<!--'column'是数据库的字段,'property'是实体类的属性-->
<select id="getUserById" parameterType="int" resultMap="Usermap">
    select * from mybatis.user where id=#{id}
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素的,它的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

  • MyBatis 会在幕后自动创建一个 ResultMap,再根据属性名来映射列到 JavaBean 的属性上。如果列名和属性名不能匹配上,可以在 SELECT 语句中设置列别名(这是一个基本的 SQL 特性)来完成匹配,比如:

    <select id="selectUsers" resultType="User">
      select
        user_id             as "id",
        user_name           as "userName",
        hashed_password     as "hashedPassword"
      from some_table
      where id = #{id}
    </select>
    
  • 这就是 ResultMap 的优秀之处——你完全可以不用显式地配置它们。

6、日志

6.1 日志工厂

如果数据库操作出现异常,就需要打印日志来排错!

Mybatis 通过使用内置的日志工厂提供日志功能。内置日志工厂将会把日志工作委托给下面的实现之一:

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Log4j
  • JDK logging

STDOUT_LOGGING标准日志输出

在mybatis-config.xml配置

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

6.2 Log4j

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

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  2. 写配置文件log4j.properties(名字一定不能错!

    #将等级为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/Test.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. 在mybatis-config.xml配置

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    
  4. 测试

简单使用

  • 导包别导错了:import org.apache.log4j.Logger

  • 日志对象,参数是当前类的Class对象

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

    logger.info("进入了testLog4j方法");
    logger.debug("进入了testLog4j方法");
    logger.error("进入了testLog4j方法");
    

7、分页

7.1 使用Limit分页

语法:select *from user limit startIndex,pageSize;
select *from user limit n;	#[0,n)
注意:表的记录索引从0开始
  1. 写接口

    //Limit分页
    List<User> getUserByLimit(Map map);
    
  2. 写配置

    <select id="getUserByLimit" parameterType="map" resultMap="Usermap">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>
    
  3. 测试

    //测试limit
    @Test
    public void getUserByLimitTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<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) {
            logger.info(user);
        }
        sqlSession.close();
    }
    

7.2 使用RowBounds分页

在java代码层面实现分页

  1. 写接口

    //Rowbounds分页
    List<User> getUserByRowbounds();
    
  2. 写配置

    <select id="getUserByRowbounds" resultMap="Usermap">
        select *from mybatis.user
    </select>
    
  3. 测试

    //测试Rowbounds
    @Test
    public void getUserByRowboundsTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        RowBounds rowBounds = new RowBounds(0,2);
        List<User> userList = sqlSession.selectList("com.xiaojing.dao.UserMapper.getUserByRowbounds", null, rowBounds);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

8、使用注解开发

注解的核心是反射机制

  1. 在接口上方写注解

    public interface UserMapper {
        @Select("select *from mybatis.user")
        List<User> getUser();
            @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 insertUser(User user);
    
        @Insert("insert into user(name,pwd) values (#{name},#{password})")
        int insertUser(Map map);
    
        @Update("update user set pwd=#{password} where name=#{name}")
        int updateUser(Map map);
    
        @Delete("delete from user where id=#{iod}")
        int deleteUser(@Param("iod")int id);
    }
    
  2. 测试

    @Test
    public void getUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUser();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
    }
    
    @Test
    public void insertUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, String> map = new HashMap<String, String>();
        map.put("name","麻子");
        map.put("password","1234");
        mapper.insertUser(map);
        sqlSession.commit();
    }
    
    @Test
    public void updateUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, String> map = new HashMap<String, String>();
        map.put("name","老马");
        map.put("password","4321");
        mapper.updateUser(map);
        sqlSession.commit();
    }
    
    @Test
    public void deleteUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(2);
        sqlSession.commit();
    }
    
  • 使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。
  • 选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。 换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和 XML 的语句映射方式间自由移植和切换。

关于@Param()注解

  • 基本类型的参数或者包装类
  • 引用类型不需要加
  • sql语句中引用的参数就是@Param里设置的参数值

9、Mybatis执行流程分析

在这里插入图片描述

10、Lombok(偷懒专用)

Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

使用步骤:

  1. 下载插件
  2. 导入jar包
  3. 在实体类加注解即可

注解说明:

@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
@NoArgsConstructor	//无参构造
@AllArgsConstructor	//有参构造
@Data	//无参构造,get and set,toString,hashcode,equals

11、多对一、一对多处理

  • 多对一:关联 association 比如:多个学生对应一个老师
  • 一对多:集合 collection 比如:一个老师有多个学生

11.1 多对一

测试环境搭建

  1. 导入lombok

  2. 新建实体类Teacher,Student

    @Data
    public class Student {
        private int id;
        private String name;
        private Teacher teacher;
    }
    
    @Data
    public class Teacher {
        private int id;
        private String name;
    }
    
  3. 建立Mapper接口

  4. 建立Mapper.xml文件

  5. 在mybatis-config.xml绑定Mapper

  6. 测试

按照查询嵌套处理

<!--思路:
1、查询出所有学生
2、根据tid查询其对应老师
-->
<resultMap id="studentTeacher" type="student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的对象就用association和collection-->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getStudent" resultMap="studentTeacher">
    select * from student
</select>
<select id="getTeacher" resultType="teacher">
    select *from teacher where id=#{id}
</select>

按照结果嵌套处理

<select id="getStudent2" resultMap="studentTeacher2">
    select s.id sid,s.name sname,t.name tname
    from student s,teacher t
    where s.tid=t.id
</select>
<resultMap id="studentTeacher2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

11.2 一对多

测试环境与多对一差不多,实体类有所改变:

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

建议按结果嵌套查询

<select id="getTeacher" resultMap="teacherStudent">
    select t.id tid,t.name tname,s.id sid,s.name sname
    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"/>
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

ofType & javaType

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

注意点:

  1. 保证SQL的可读性
  2. 注意一对多和多对一中,属性名和字段的问题

面试高频:

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

12、动态sql

理解:动态sql就是根据不同的条件生成不同sql语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

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

12.1 环境搭建

  1. 创建一个测试博客表

    CREATE TABLE `blog`(
    `id` INT(10) NOT NULL COMMENT '博客id',
    `title` VARCHAR(20) NOT NULL COMMENT '博客标题',
    `author` VARCHAR(10) NOT NULL COMMENT '作者',
    `create_time` DATETIME NOT NULL COMMENT '创建时间',
    `views` INT(20) NOT NULL COMMENT '浏览量'
    )ENGINE=INNODB CHARSET=utf8;
    
  2. 创建一个基础工程

    • 导包

    • 配置xml文件

    • 编写实体类

      @Data
      @AllArgsConstructor
      public class Blog {
          private String id;
          private String title;
          private String author;
          private Date createTime;
          private int views;
      }
      
    • 编写实体类对应的接口和Mapper映射

      int addBlog(Blog blog);
      
      <insert id="addBlog" parameterType="blog">
          insert into mybatis.blog(id,title,author,create_time,views)
          values (#{id},#{title},#{author},#{createTime},#{views})
      </insert>
      

12.2 IF

接口

//用if查询
List<Blog> queryBlogIF(Map map);

xml

<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <if test="views != null">
        where views > #{views}
    </if>
    <if test="author != null">
        and author=#{author}
    </if>
    <if test="title != null">
        and title like #{title}
    </if>
</select>

12.3 choose (when, otherwise)

类似switch…case…default语句

接口

//用choose查询
List<Blog> queryBlogChoose(Map map);

xml

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

12.4 trim (where, set)

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

<where>
    <if test="views != null">
        views > #{views}
    </if>
    <if test="author != null">
        and author=#{author}
    </if>
    <if test="title != null">
        and title like #{title}
    </if>
</where>

set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。

//用set更新
int updateBlogSet(Map map);
<update id="updateBlogSet" parameterType="map">
    update mybatis.blog
    <set>
        <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>

所谓的动态sql,其本质还是sql语句,只是在sql层面加了逻辑代码

12.5 SQL片段

简化重复的sql语句,实现代码复用

<sql id="set-test">
    <if test="title != null">title=#{title},</if>
    <if test="author != null">author=#{author},</if>
    <if test="views != null">views=#{views}</if>
</sql>
<update id="updateBlogSet" parameterType="map">
    update mybatis.blog
    <set>
        <include refid="set-test"></include>
    </set>
    where id=#{id}
</update>

12.6 Foreach

接口

//用foreach查询
List<Blog> queryBlogForeach(Map map);

xml

<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
		/*此处的collection是一个list,所以map需要传入一个list来进行遍历*/
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
        <if test="views != null">
            and views>=#{views}
        </if>
    </where>
</select>

测试

@Test
public void queryBlogForeachTest(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    List<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    ids.add(4);
    map.put("ids",ids);
    map.put("views",100);
    List<Blog> blogList = mapper.queryBlogForeach(map);
    for (Blog blog : blogList) {
        System.out.println(blog);
    }
    sqlSession.close();
}

建议:先在Mysql中写sql语句,然后再在动态sql中拼接

13、缓存

13.1 简介

查询:连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方——内存:缓存
那么我们再次查询的时候就可以不用走数据库了
  1. 缓存【Cache】?
    • 存在内存中的临时数据
    • 将用户经常查询的数据放在缓存中,用户查询的时候就不用从磁盘上查询了,而从缓存中查询,提高查询效率
  2. 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销
  3. 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据

13.2 Mybatis缓存

Mybatis系统中默认顶一个两级缓存:一级缓存和二级缓存

  • 默认情况下,只有一级缓存开启。这是sqlSession级别的,随着Session开启而开启,关闭而关闭,也称其为本地缓存
  • 二级缓存是namespace级别的,需要手动开启和配置
  • Mybatis有一个配置缓存的接口Cache,可以定义二级缓存

注意事项:

  • 映射语句文件中的所有 select 语句的结果将会被缓存。
  • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
  • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
  • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
  • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
  • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

13.3 一级缓存

一级缓存也叫本地缓存:

  • 在域数据库交互的同一个会话中,会将查过的数据放在缓存中
  • 以后再查询相同的数据时,直接从缓存中取数据

测试

  • 开启日志

  • 测试两次查询同一条数据

  • 手动清理缓存

    public void getUserIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.clearCache();//手动清理缓存
        System.out.println("============================");
        User user1 = mapper.getUserById(1);
        System.out.println(user1);
        System.out.println(user==user1);
        sqlSession.close();
    

小结:一级缓存默认开启,且在一个sqlSession内有效

13.4 二级缓存

二级缓存是基于namespace的缓存,它的作用域比一级大

  • 我们希望当会话关闭的时候,存储在一级缓存的数据可以进入二级缓存
  • 用户进行第二次会话的时候,就可以直接从二级缓存拿数据

步骤:

  1. 显示的开启全局缓存

    <setting name="cacheEnabled" value="true"/>
    
  2. 在对应的Mapper.xml开启cache

    <cache/>
    

    也可以自定义cache

    <cache
      eviction="FIFO"
      flushInterval="60000"
      size="512"
      readOnly="true"/>
    
  3. 测试

    public void getUserIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        SqlSession sqlSession1 = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();//关闭第一个会话,数据进入二级缓存
        System.out.println("============================");
    
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = mapper1.getUserById(1);
        System.out.println(user1);
    
        System.out.println(user==user1);
        sqlSession.close();
    }
    

小结:当开启二级缓存后,会话事务提交或者会话结束,数据都会进入二级缓存。

13.5 缓存原理

image-20200821224215480.png

小结:当开启二级缓存后,会话事务提交或者会话结束,数据都会进入二级缓存。

13.6 自定义缓存(了解)

Ehcache是一种广泛使用的开源Java分布式缓存

配置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 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"/>
</ehcache>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值