Mybatis学习笔记

文章目录

MyBatis

前情回顾

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

1.MyBatis简介

在这里插入图片描述

1.1什么是Mybatis

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

如何获得Mybatis

  • maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html
  • Github:https://github.com/mybatis/mybatis-3

1.2 持久化

数据持久化

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

为什么需要持久化?

  • 有的资源断电及失

  • 不想丢掉一些对象

  • 内存太贵

1.3 持久层

之前学过的一些层:Dao层,Service层(调用dao层的业务工作),Controller层(接受用户的请求,并把请求转发给下面的service层去做)…(每个层都有具体的业务)

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

1.4 为什么需要Mybatis?

  • 帮助程序猿将数据存入到数据库中
  • 方便
  • 传统的JDBC代码太复杂,简化–>框架–>自动化
  • 不用Mybatis也可以,只是它更容易上手
  • 优点:
    简单易学,灵活,sql和代码分离,提高了可维护性,提供映射标签,支持对象与数据库的orm字段关系映射
    提供对象关系映射标签,提供xml标签,支持编写动态sql
  • 最重要的一点:使用的人多!
    Spring-SpringMVC-SpringBoot

2.第一个Mybatis程序

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

2.1创建数据库和数据表:

CREATE DATABASE `mybatis`;
use `mybatis`;

CREATE TABLE `user`(

`id` INT(20) NOT NULL PRIMARY KEY,
`name`	VARCHAR(30) DEFAULT NULL,
`pwd`	VARCHAR(30) DEFAULT NULL

)ENGINE=INNODB DEFAULT CHARSET=utf8;

在这里插入图片描述

2.2新建maven项目

  • 新建一个普通maven项目
  • 删除src目录
  • 导入maven依赖
<!--import dependencies-->
    <dependencies>
        <!--mysql driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.3 创建一个模块

  • 编写mybatis的核心配置文件

jdbc资源文件内容(本机的):

username=root
password=000000
url=jdbc:mysql://localhost:3306/book?serverTimezone=GMT%2B8			//book为数据库名称
driverClassName=com.mysql.cj.jdbc.Driver
initialSize=5
maxActive=10

以下为mybatis-config.xml文件放在 src/main/resources 下

<?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 core file-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="000000"/>
            </dataSource>
        </environment>
    </environments>

    <!--a Mapper.xml need regist in Mybatis core configuration file-->
    <mappers>
        <mapper resource="com/guo/dao/UserMapper.xml"/>
    </mappers>
</configuration>

此处设useSSL=false。

在这里插入图片描述

2.3.1上面配置文件的注意事项(老数据库问题了):

①driver属性:由于我的Mysql版本是8.0.22,所以值为:com.mysql.cj.jdbc.Driver,而非com.mysql.jdbc.Driver
②url属性:由于版本值在jdbc:mysql://localhost:3306/databasename?serverTimezone=GMT%2B8

  • 编写mybatis的工具类(目的就是来获取SqlSessionFactory对象的)

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。

//SqlSessionFactory -->SqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {

        try {
            //使用Mybaties第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
//        SqlSession sqlSession =  sqlSessionFactory.openSession();
//        return sqlSession;

        return sqlSessionFactory.openSession();
    }

}

2.3.2其中有提升作用域的思想:

起初为:

    static {

        String resource ="mybatis-config.xml";//放在静态代码块里,一初始就加载
        InputStream inputStream = null;
        try {
            //使用Mybaties第一步:获取sqlSessionFactory对象
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

但是由于在下方无法调用到所生成的对象因此要提升作用域:
这样一来就可以获取到静态的代码块所生成对象

private static SqlSessionFactory sqlSessionFactory;

static {

    String resource ="mybatis-config.xml";//放在静态代码块里,一初始就加载
    InputStream inputStream = null;
    try {
        //使用Mybaties第一步:获取sqlSessionFactory对象
        inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static SqlSession getSqlSession(){
    sqlSessionFactory
}

2.4编写实体类和dao层代码

2.4.1实体类

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

2.4.2dao接口

public interface UserDao {//此时的dao等价于以后的mapper
    List<User> getUserList();
}

2.4.3接口实现类

(以前是通过实现类的操作来实现方法)----->>>>现在是通过xml文件直接配置的

以后通过xml配置文件的方式实现

由原来的UserDaoImpl转变成为一个Mapper配置文件,放在dao层的文件夹

<?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.guo.dao.UserDao">//指明了需要实现方法的接口

    <!--sql-->
    <select id="getUserList" resultType="com.guo.pojo.User">//标签的id就相当于原来重写方法的名字
        select * from mybatis.user   	//要执行的sql语句
    </select>
</mapper>

在这里插入图片描述

resultMap返回多个对象(相当于集合),resultType返回一个对象

2.5编写测试代码

  • Junit测试

  • 注意点:

    org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.(这个异常)
    这个异常为mybatis-config.xml文件中没有配置mapper标签

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

    测试类:

    @Test
        public void test(){
            //第一步:获得SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            //方式一:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
    
            for (User user : userList) {
                System.out.println(user);
            }
            //关闭SqlSession
            sqlSession.close();
        }
    
    

    可能遇到的问题:

    1. 配置文件没有注册;

    2. 绑定接口错误;

    3. 方法名不对;

    4. 返回类型不对;

    5. Maven导出资源问题。解决XML资源找不到的问题
      Maven导出资源问题在Maven中提到过在Build中配置resource来防止我们资源出现导出的问题
      在maven的pom.xml中配置

      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                      <includes>
                          <include>**/*.properties</include>
                          <include>**/*.xml</include>
                      </includes>
          </resource>
              <resource>
              <directory>src/main/java</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
              <filtering>true</filtering>
              </resource>
          </resources>
      </build>
      

在这里插入图片描述

配置完成之后发现在target包下生成了xml文件,之前是生成不了的
小tips:还遇到的问题
在这里插入图片描述

这里需要添加一个分隔符,如果不添加Mysql会爆出连接失败异常。
结果:
在这里插入图片描述
当数据库字段为带下划线字段时,如果没有在mybatis配置文件中进行配置会导致查询出的数据为null,因此需要在配置文件中进行配置内容因此需要在mybatis-config.xml文件中添加setting配置标签

<configuration>
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

个人理解:

1.Mybatis所目前来看所实现的功能和JDBCUtils实现的功能是一样的,Mybatis可以说是简化了实现dao接口的步骤而是直接通过xml配置文件进行实现;
2.相对于之前的druid连接池通过QueryRunner的对象来执行sql语句,mybatis是通过获得Sqlsession对象来执行sql语句的

Mybatis的三个核心接口

①SqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。
你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

②SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在(所以用完需要close),没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

③SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。 下面的示例就是一个确保 SqlSession 关闭的标准模式:(建议)

try (SqlSession session = sqlSessionFactory.openSession()) {
  // 你的应用逻辑代码
}

SqlSessionFactoryBuilder------>SqlSessionFactory------>SqlSession

回忆流程:

①写MybatisUtils文件
②工具类被迫的需要一个配置文件,去resources文件夹写入mybatis-config.xml文件
③编写实体类User,创建dao层的UserDao接口
④实现UserDao接口的实现类,只不过现在是用xml配置文件的方式进行配置
⑤编写测试类
⑥如果有错误,看maven导出资源的build标签是否写入

3、CRUD(增删改查)

3.1 namespace

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

<mapper namespace="com.guo.dao.UserDao">
</mapper>

3.2 select

选择,查询语句;

  • id:就是对应的namespace中的方法名(建议直接去接口中复制的啦);
  • resultType:Sql语句执行的返回值!
  • parameterType:参数类型!
<mapper namespace="com.guo.dao.UserDao">
    <select id="getUserList" resultType="com.guo.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

当需要传入值执行sql语句时:
1.编写接口

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

2.编写对应的mapper中的sql语句

	<select id="getUserById" parameterType="int" resultType="com.guo.pojo.User">
        select * from mybatis.user where id = #{id}
	</select>

3.测试

    @Test
    public void test2(){
        
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        
        User user = mapper.getUserbyId(1);
        System.out.println(user);
        sqlSession.close();
    }

结果:
在这里插入图片描述

3.3 Insert

接口中添加方法

    int addUser(User user);   	//返回所受影响行数

需要用到insert标签

<insert id="addUser" parameterType="com.guo.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>

小tips:
想让这里sql语句自动识别为mysql语句,需要去setting中配置一下SQL Dialects为MySQL
在这里插入图片描述

测试

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

        User user = new User(3,"郭万","000000");
        mapper.addUser(user);
    }

这里会遇到一个问题,执行完方法后表中数据没有变化,是因为数据库的增删改需要提交事务这一点和JDBC是一样的
因此需要添加commit方法
最终测试:

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

        User user = new User(3,"郭万","000000");
        int res = mapper.addUser(user);
        sqlSession.commit(); //提交数据库事务,若不执行会添加失败
        if(res>0) {
            System.out.println("添加完成");
        }else {
            System.out.println("添加失败");
        }

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

        User user = new User(3,"郭万","000000");
        mapper.addUser(user);
    }

结果:
在这里插入图片描述

3.4update

	<update id="updateUser" parameterType="com.guo.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>

3.5delete

    <delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>

3.6分析错误

错误1:xml文件中注释不能出现中文报错,查看自己的是UTF-8还是GBK编码,改成为相应的就行

<?xml version="1.0" encoding="UTF-8" ?>
<?xml version="1.0" encoding="GBK" ?>

即可成功测试。

  • 标签不要匹配错!
  • resource绑定mapper,需要使用路径!
  • 程序配置文件必须符合规范!
  • NullPointerException,没有注册到资源!
  • maven资源没有导出问题!

3.7万能的Map

假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
这样例如我们在插入一个对象user时,不需要创建一个新的user对象,(因为创建实例要赋值很多的属性,当属性过多的时候就会比较麻烦),而是用键值对的形式去传递参数。

//万能的Map
    int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来  传递map的key-->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,pwd) values (#{userid},#{password})
    </insert>

测试:

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

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

         mapper.addUser2(map);

         sqlSession.commit();
         sqlSession.close();
     }

  • Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
  • 对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
  • 只有一个基本类型参数的情况下,可以直接在sql中取到!
  • 多个参数用Map,或者注解!

3.8模糊查询

模糊查询怎么写?(要注意sql注入的问题)
①Java代码执行的时候传递通配符% %

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

②在Sql拼接中使用通配符

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

4.配置解析

4.1核心配置文件

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

在这里插入图片描述

红框为需要重点理解的,剩下的了解即可

4.2 环境配置(environments)

Mybatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境。
学会使用配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池:POOLED(当然还有别的类型)

4.3 属性(properties)

我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素来传递。【db.properties】

注意:
在这里插入图片描述

编写一个配置文件
db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=000000
	<!--引入外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </properties>

优化后的核心配置文件代码:

<?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 core file-->
<configuration>
    <properties resource="db.properties"/>

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

    <!--a Mapper.xml need regist in Mybatis core configuration file-->
    <mappers>
        <mapper resource="com/guo/dao/UserMapper.xml"/>
    </mappers>

</configuration>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的!

4.4 类型别名(typeAliases)

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

插入代码后,之前素有需要为com.guo.pojo.User可以全部变为User

也可以指定一个包名,MyBatis会在包名下面搜索需要的JavaBean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

	<!--可以给实体类起别名-->
    <typeAliases>
        <package name="com.guo.pojo"/>
    </typeAliases>

4.5 设置(Settings)

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

额外知识:为什么数据库使用驼峰命名last_name
需要记忆的setting:

在这里插入图片描述

4.6 其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    1. mybatis-generator-core
    2. mybatis-plus
    3. 通用mapper

4.7 映射器(mappers)

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

以后每写一个dao就会写一个mapper.xml文件

方式一:【推荐使用】

    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
    <mappers>
        <mapper resource="com/guo/dao/UserMapper.xml"/>
    </mappers>

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

    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
    <mappers>
        <mapper class="com.guo.dao.UserMapper"/>
    </mappers>

注意点(如果不注意可能会出问题):

  • 接口和它的Mapper配置文件必须同名!
  • 接口和它的Mapper配置文件必须在同一个包下!
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E019jGmy-1618209388579)(C:\Users\GuoSheng\AppData\Roaming\Typora\typora-user-images\image-20210326152903480.png)]

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

    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
    <mappers>
        <package name="com.guo.dao"/>
    </mappers>

注意点:

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

练习:

  • 将数据库配置文件外部引入
  • 实体类别名
  • 保证UserMapper接口和UserMapper.xml改为一致!并且放在同一个包下!

4.8 生命周期和作用域

生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
画图工具https://www.processon.com/

在这里插入图片描述

SqlSessionFactoryBuilder:

  • 一旦创建了 SqlSessionFactory,就不再需要它了。
  • 所以要设置为局部变量

SqlSessionFactory:

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

SqlSession:

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

在这里插入图片描述

这里面的每一个mapper,就代表一个具体的业务。

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

5.1 问题

数据库中的字段

在这里插入图片描述

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User {
    private int id;
    private String name;
    private String password;
}

测试出现问题(原因是pojo类的属性和数据库的字段不一致)
在这里插入图片描述

解决方法:
①起别名

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

②resultMap

5.2 resultMap

结果集映射

原来是(数据库):id name pwd
实体类:		id name password
所以要想办法让数据库列的结果编程实体类的属性
    <!--  结果集映射  -->
    <resultMap id="UserMap" type="User">
        <!--column数据库中的字段,property实体类中的属性-->
        <result  property="id" column="id" />
        <result  property="name" column="name" />
        <result  property="password" column="pwd" />
    </resultMap>

    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

让数据库中的列映射到属性当中的字段(比较复杂的情况----字段也为对象)

  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。
  • 它可能不仅要赋值一些基本元素,还可以赋值一些实体类POJO

只需要映射与字段不一样的内容因此可以修改为:

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

在这里插入图片描述

6.日志

6.1日志工厂

如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手!
目的就是想把sql语句给输出。
曾经:sout、debug
现在:日志工厂!

在这里插入图片描述

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

STDOUT_LOGGING为标准日志输出
在mybatis-config.xml核心配置文件中,配置我们的日志!

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

在这里插入图片描述

6.2 Log4j

什么是Log4j?

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

①先在pom.xml文件中导入log4j的依赖包

    <dependencies>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

②在resources文件夹下建立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/guo.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

③在mybatis-config.xml核心配置文件中,配置log4j为日志的实现!

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

测试结果:
在这里插入图片描述

生成的log文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iqxTC852-1618209388606)(C:\Users\GuoSheng\AppData\Roaming\Typora\typora-user-images\image-20210326201419799.png)]

的简单使用**

  1. 在要使用Log4j的测试类中,导入包import org.apache.log4j.Logger;
  2. 日志对象,参数为当前类的class
public class LogTest {
    static Logger logger = Logger.getLogger(LogTest.class);
    
    @Test
    public void logttest(){
        logger.info("info:进入了testLog4j");
        logger.debug("DEBUG:进入了testLog4j");
        logger.error("erro:进入了testLog4j");

    }
}

测试结果:
在这里插入图片描述

真实场景:作为一些记录

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

    List<User> userList = mapper.getUserList();
    logger.info("进入了test1测试方法");

    System.out.println(userList);

    sqlSession.close();
}

7.分页

思考:为什么需要分页?
答:减少数据的处理量

7.1使用Limit分页

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

使用Mybatis实现分页,核心其实就是SQL

①接口中添加方法

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

②Mapper.xml

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

③测试:

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

        Map<String,Integer> map =new HashMap<String, Integer>();
        
        map.put("startIndex",1);
        map.put("pageSize",3);

        List<User> userByLimit = mapper.getUserByLimit(map);

        System.out.println(userByLimit);

        sqlSession.close();
    }

7.2 RowBounds分页(了解为主开发中不建议使用)

到目前为止我们的核心都是在与写Sql语句,没有面向的对象思想,为了体现java的特性RowBounds诞生
不再使用SQL实现分页

①接口中添加抽象方法

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

②Mapper.xml

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

③测试

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

        //RowBounds实现
        RowBounds rowBounds = new RowBounds(0, 2);

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

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

7.3分页插件

https://pagehelper.github.io/

在这里插入图片描述

小tips:在执行测试时,出现xml文件中字符集的问题解决办法:

①删掉中文注释
②将第一行字符集utf-8改为utf8

8.使用注解开发

8.1面向接口编程

  • 之前学过面向对象编程,也学习过接口,但在真正的开发中,很多时候会选择面向接口编程。

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

  • 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;

  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

8.2 使用注解开发

①注解在UserMapper接口上实现,并删除UserMapper.xml文件

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

②需要在mybatis-config.xml核心配置文件中绑定接口

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

③测试

    @Test
    public void getUsers(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();

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

        sqlSession.close();
    }

官方推荐:

需要执行比较麻烦的sql语句还是推荐使用xml文件

本质:反射机制实现
底层:动态代理!
在这里插入图片描述

Mybatis详细的执行流程!(之后应用的多了详细再走一遍)

8.3使用注解完成CRUD

我们可以在创建工具类的时候实现自动提交事务,之前是需要在测试的时候执行sqlsession.commit的操作

当然是在执行增删改时需要提交事务

之前在MybatisUtils类中使用的无参构造器:

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

①现在我们需要设置其中的参数为true表示为自动提交

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

②编写接口,增加注解

public interface UserMapper {

    @Select("select * from user")
    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},#{pwd})")
    int addUser(User user);

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

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

测试:

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

        User userById = mapper.getUserById(5);
        System.out.println(userById);
    }

【注意:我们必须要将接口注册绑定到我们的核心配置文件中!】
注意引入resource和class的文件格式不同哦

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

        <mapper class="com.guo.dao.UserMapperplus"/>

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果方法中只有一个基本类型的话,可以忽略,但是建议都加上!
  • 我们在SQL中引用的就是我们这里的@Param(“”)中设定的属性名!
    #{}和${}区别
  • 尽量使用#{}:可以防止sql注入,而$不能。

在这里插入图片描述

9.Lombok

再也不需要些get,set,equals等方法了,只需要在实体类上添加注解即可

使用步骤:

  1. 在IDEA中安装Lombok插件!

    在这里插入图片描述

  2. 在项目pom.xml文件中导入Lombok的jar包

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

3.在实体类上添加注解即可(使用在spirngmvc笔记中有哦)

@Data   	//自动生成getset方法
@AllArgsConstructor			//自动生成全参构造器
@NoArgsConstructor			//自动生成无参构造器

Lombok的优缺点
优点:
①能通过注解的方式简化我们的代码,getter、setter、hashcode、tostring等
②让代码变得简洁
③维护简便
缺点:
不支持多种参数构造器的重载

lombok对于IDEA2020.2会遇到的bug
在导入注解之后,发现原来的java文件失去了标识:
在这里插入图片描述
因此需要修复这个bug
①首先下载jar包
链接:https://pan.baidu.com/s/1zP3rOm6Ac1r1wgh73I-EGw
提取码:1w3a
这是下载后的样子:
在这里插入图片描述
②去IDEA的file->settings->Plugins->Lombok
在这里插入图片描述
然后找到刚刚下载的补丁包,直接选择就是了,然后会重启IDEA即可。

10.数据库中的多对一处理

多对一情景:

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

①创建两个表

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. 导入Lombok

  2. 新建实体类Teacher,Student

    package com.guo.pojo;
    
    import lombok.Data;
    
    @Data
    public class Student {
        private String name;
        private int id;
        private Teacher teacher;
    }
    
    
    package com.guo.pojo;
    
    import lombok.Data;
    
    /**
     * @ClassName Teacher
     * @Description TODO
     * @Author GuoSheng
     * @Date 2021/3/27  18:40
     * @Version 1.0
     **/
    @Data
    public class Teacher {
        private String name;
        private int id;
    
    }
    
  3. 建立Mapper接口
    在这里插入图片描述

  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">
    <!--configuration core file-->
    <mapper namespace="com.guo.dao.TeacherMapper">
    </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">
    <!--configuration core file-->
    <mapper namespace="com.guo.dao.StudentMapper">
    </mapper>
    
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--configuration core file-->
    <configuration>
    
        <properties resource="db.properties"/>
    
        <settings>
            <setting name="logImpl" value="LOG4J"/>
        </settings>
    
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                    <property name="url" value="${url}"/>
                    <property name="driver" value="${driver}"/>
                </dataSource>
            </environment>
        </environments>
    
    
        <!--a Mapper.xml need regist in Mybatis core configuration file-->
        <mappers>
            <mapper class="com.guo.dao.TeacherMapper"/>
            <mapper class="com.guo.dao.StudentMapper"/>
        </mappers>
    
    </configuration>
    
  6. 测试查询是否能够成功!

    public class OtoDTest {
        @Test
        public void test1(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
            Teacher teacherById = mapper.getTeacherById(1);
            System.out.println(teacherById);
            sqlSession.close();
        }
    }
    

    测试查找学生的方法:
    发现Teacher的属性为null

    因此要解决这个问题:(要用到配置文件来而不是注解了)

    思路:
    ①查找出所有的学生
    ②根据查找出来学生tid,寻找对应的老师

因为这下需要用到dao接口对应的配置文件,所以之前的注解方法需要删掉重写编写

10.1嵌套的查询执行sql返回为javapojo对象或者list集合

首先在xxxmapper.xml文件中添加mapper标签,namespace对应接口地址

<mapper namespace="com.guo.dao.StudentMapper">
</mapper>

添加因为此时要做的是查找,插入查找标签设置id(为对应方法名字)和返回值

    <select id="getAllStudent" resultMap="StudentTeacher">
        select * from student
    </select>

注意这里的resultMap是自定义的一个类型,其实返回的是一个学生类
因此要继续编写resultMap标签来配置这个

<resultMap id="StudentTeacher" type="com.guo.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
</resultMap>

但是由于在Student类中第三个属性Teacher为一个java类,而对应到数据表中仅为一个tid(int)

所以这里要用到嵌套查询

 <!--复杂的属性,我们需要单独处理       返回对象:association      返回集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>

在这里插入图片描述

最终的mapper全部代码:

<mapper namespace="com.guo.dao.StudentMapper">

    <select id="getAllStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    <resultMap id="StudentTeacher" type="com.guo.pojo.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="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>
</mapper>

10.2按照sql语句的查询结果嵌套处理

    <!--按照结果嵌套处理    -->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from mybatis.student s,mybatis.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>

回顾mysql多对一查询方式:

  • 子查询
  • 联表查询

11.一对多的处理

比如:一个老师拥有多个学生!
对于老师而言,就是一对多的关系!

搭建环境:

1.环境搭建和之前一样
实体类:Student类

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

}

Teacher类:

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

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

编写 接口中的抽象方法:

    Teacher getTeacher(@Param("tid") int id);

11.1按照SQL语句的结果嵌套处理

    <!--    按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
            SELECT  s.id sid,s.name sname,t.name tname,t.id,tid
            from student s,teacher t
            where s.tid = t.id and t.id = #{tid}
    </select>

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

图解思路:
在这里插入图片描述

11.2按照查询嵌套处理

    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from mybatis.teacher where id = #{tid}
    </select>

    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
    </resultMap>

    <select id="getStudentByTeacherId" resultType="Student">
        select * from  mybatis.student where tid = #{tid}
    </select>

解惑:

在这里插入图片描述
嵌套查询中的sql语句的值可以随意命名

小结

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

注意点:

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

面试高频

12.动态SQL

12.1什么是动态sql

动态sql就是指,根据不同的条件生成不同SQL语句

利用动态SQL这一特性可以彻底摆脱这种痛苦。

在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

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

搭建环境

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

创建一个基础工程

  1. 导包
  2. 编写配置文件
  3. 编写实体类
@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime; //属性名和字段名不一致
    private int views;
}

4.编写实体类对应的Mapper接口和Mapper.xml文件

package com.guo.dao;

public interface BlogMapper {
}

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

</mapper>

编写IUtils来获取一个随机的id

package com.guo.utils;

import java.util.UUID;


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

此时要注意前面的坑,pojo类的属性和数据库的列名不一致因此要在核心配置文件中继续配置

在这里插入图片描述
去接口对应的xml文件中配置insert标签实现插入方法

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

测试:

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

        mapper.addBlog(new Blog(IUtils.getId(),"郭帅真的帅","郭帅",new Date(),999));

        System.out.println("插入成功");
        sqlSession.close();
        
    }

在这里插入图片描述

12.2动态SQL-IF语句

    List<Blog> queryBlogIF(Map map);
    <select id="queryBlogIF" parameterType="map" resultType="Blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>

测试:

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

        Map map =new HashMap();
        map.put("title","spring1");

        List<Blog> blogs = mapper.queryBlogIF(map);
        System.out.println(blogs);
        sqlSession.close();
    }

说白了就是通过map的put方式来动态的改变查找条件来实现查找

12.3动态SQL-trim(where,set)

where发现多余的and和or会自动删除然后合并sql语句

set在执行update时,发现多余的逗号(,)会删除然后合并sql语句

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

之前where是一个关键字,而动态sql将where设置为一个标签直接后面添加要执行的语句,where标签会自动删除前面的and或or(前提是前面没有条件语句)

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

    </select>

    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

12.4choose - when - otherwise

可以理解为java的switch

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

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

12.5SQL片段

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

  1. 使用SQL标签抽取公共的部分
  <sql id="if-title-author">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>

2.在需要使用的地方使用Include标签引用即可

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

注意事项:

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

12.6Foreach

  • 动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。
  • foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
  • 提示:你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<!--select * from blog where 1=1 and (id=1 or id=2 or id=3)
    我们现在传递一个万能的map,这map中可以存在一个集合!
    -->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

动态SQL的自我理解:

主要用到了map来传参实现了让SQL语句灵活的变化(查询条件),你可以理解为类似于java中append添加,主要是通过内容的拼接实现的

13.缓存(了解即可)

13.1简介

查询过程:连接数据库,耗资源
一次查询的结果,给它暂时存在一个可以直接取到的地方!---->内存:缓存
我们再一次查询相同数据的时候就不需要去数据库查询,直接走缓存

13.1.1.什么是缓存[Cache]

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

13.1.2.为什么使用缓存

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

13.1.3什么样的数据能使用缓存

  • 经常查询并且不经常改变的数据【可以使用缓存】

13.2Mybatis缓存

Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,缓存可以极大的提升查询效率。
Mybatis系统中默认定义了两级缓存:一级缓存二级缓存

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

13.3一级缓存

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

测试步骤:

  1. 开启日志!

    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    
  2. 测试在一个Session中查询两次相同记录

        public void test4(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            Blog blog1 = mapper.queryBlogById(1);
            System.out.println(blog1);
            Blog blog2 = mapper.queryBlogById(1);
            System.out.println(blog2);
    
            System.out.println(blog1==blog2);
    
            sqlSession.close();
        }
    
  3. 查看日志输出
    在这里插入图片描述

缓存失效的情况:
1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存。

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

13.4二级缓存

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

步骤:
1.在mybatis-config.xml开启全局缓存

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

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

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

也可以自定义参数

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>

3.测试
如果报错为:

Cause: java.io.NotSerializableException: com.kuang.pojo.User

原因是实体类没有序列化,需要给实体类实现一个序列化接口

public class Blog implements Serializable {

小结:

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

13.5缓存原理

在这里插入图片描述

在这里插入图片描述

13.6自定义缓存-ehcache(可以了解)

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

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

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

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

目前:Redis数据库来做缓存!K-V

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值