MyBatis基础笔记

1.MyBatis

是一个持久层框架,MyBatis默认的事务管理器就是JDBC 连接池POOLED,可以配置多个环境,但是每个SqlSessionFactory实例只能选择一种环境

2.第一个MyBatis程序

搭建环境–>导入MyBatis程序–>编写代码–>测试

2.1搭建环境

CREATE table user(
id int(20) not null PRIMARY KEY,
name VARCHAR(30) DEFAULT null,
pwd VARCHAR(30) DEFAULT null
)CHARSET=utf8;

INSERT INTO user(id,name,pwd) values
(1,'狂神','123456'),
(2,'张三','123456'),
(3,'李四','123456')

SELECT * from user;

新建项目

  1. 新建一个普通mevan项目
  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>
    </dependency>
</dependencies>

2.2创建一个模块

第一步先写工具类 然后需要写配置文件 然后写实体类 然后接口 然后Mapper.xml test

在这里插入图片描述

mybatis-config.xml配置文件

<dataSource type="POOLED">
    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true"/>
    <property name="username" value="root"/>
    <property name="password" value="1"/>
</dataSource>
  • 编写mybatis工具类
package com.kuang.utils;

//sqlSessionFactory-->sqlSession

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;

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 实例来直接执行已映射的 SQL 语句
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

2.3编写代码

实体类

package com.kuang.pojo;

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

    public User() {
    }

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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

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

Dao接口

package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;

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

接口实现类由原来的UserDao转换为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">
<!--绑定一个对应的DAO/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--    查询语句-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select> 

</mapper>

2.4 测试

这种错误 为xml文件中的UTF-8改为UTF8

Cause: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 5; 1 字节的 UTF-8 序列的字节 1 无效。

junit

package com.kuang.dao;

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

import java.util.List;

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

mybatis三个核心接口

3.CRUD

1.namespace

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

2.select

  • id:就是对应的namespace中的方法名
  • resutType:sql语句返回值
  • parameterType:参数类型

3.insert

4.update

5.delete

增删改需要提交事务

  1. 编写接口
public interface UserMapper {
    //查询全部的用户
    List<User> getUserList();
    //根据ID查询用户
    User getUserById(int id);
    //插入一个用户
    int addUser(User user);
    //修改用户
    int updateUser(User user);

    //删除一个用户
    int deleteUser(int id);
}
  1. 编写对应的Mapper中的sql语句
<mapper namespace="com.kuang.dao.UserMapper">
<!--    查询语句-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>

    <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
        select * from mybatis.user where id=#{id}
    </select>
<!--    对象中的属性可以直接取出来-->
    <insert id="addUser" parameterType="com.kuang.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name },#{pwd});
    </insert>

    <update id="updateUser" parameterType="com.kuang.pojo.User">
        update mybatis.user set name =#{name},pwd=#{pwd} where id=#{id};
    </update>
    
    <delete id="deleteUser" parameterType="com.kuang.pojo.User">
        delete from mybatis.user where id=#{id};
    </delete>
</mapper>
  1. 测试test
public class UserMapperTest {
    @Test
    public void test(){
        //1.获得sqlSession对像
        SqlSession sqlSession = MybatisUtils.getSqlSession();
       //1.方式一:getMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
@Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }
    //增删改必须需要提交事务
@Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int jack = mapper.addUser(new User(4, "jack", "123456"));
    if(jack>0){
        System.out.println("插入成功");
    }
    //提交事务
    sqlSession.commit();
    sqlSession.close();
    }
@Test
    public void getupdateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"mary","1234"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }
}

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

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

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

4.模糊查询

List<User> userlist = mapper.getUserLike("%李%");
select * from mybatis.user where name like "%"#{value}"%";/*在sql拼接中使用通配符*/

5.配置解析

属性(properties)

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

编写配置文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true
username=root
password=zhang348636

引入外部文件

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

<properties resource="db.properties"/>

5.1类型别名

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

减少类完全限定名的冗余

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

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

注解也行 注解跟别名意思差不多

@Alias("user")
//实体类
public class User {

5.2设置

在这里插入图片描述

5.3映射器

出现这个错误 要看映射器 Type interface com.kuang.dao.UserMapper is not known to the MapperRegistry.

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

方式一

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

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

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

注意

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

接口和它的Mapper文件必须在同一个包下

image-20220216163456246

6.生命周期和作用域

严重的话 会导致并发错误

在这里插入图片描述

SqlSessionFactoryBuilder

  • 一旦创建SqlSessionFactor就不再需要他了
  • 局部变量

SqlSessionFactory:

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

SqlSession:

  • 连接到连接池的一个请求
  • 不是线程安全的 因此不能共享 所以最加作用域就是请求或方法作用域

每一个Mapper就代表一个业务

7.ResultMap

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

image-20220216171930846

解决方法:起别名

select id,name,pwd as password from mybatis.user where id=#{id}

第二种解决方法:

ReaultMap:结果集映射

<mapper namespace="com.kuang.dao.UserMapper">
    <resultMap id="UserMap" type="User">
<!--        column数据库中的字段 property实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    
    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select id,name,pwd  from mybatis.user where id=#{id}
    </select>

</mapper>

ResultMap的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述他们的关系就行了

如果数据库中的字段名和实体类中的属性一致 只需要映射不一致的

8.日志

8.1日志工厂

出现异常看日志

image-20220216185645838
<settings>
	<setting name="logImpl" value="STDOUT_LOGGING"/>每一个后面绝对不能有空格
</settings>

8.2 Log4j

1.先导包

<!-- https://mvnrepository.com/artifact/log4j/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/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.配置log4j为日志的实现

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

4.Log4j的使用

image-20220216192352646

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

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

   private Logger logger = Logger.getLogger(UserMapperTest.class);

9.分页

减少数据的处理量

使用Limit分页

select * from user limit 3;默认显示前3

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

  1. 接口
List<User> getUserByLimit(Map<String,Object> map);
  1. Mapper.xml
<select id="getUserByLimit" resultMap="UserMap" parameterType="map">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
  1. 测试
@Test
public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String,Integer> map = new HashMap<>();
    map.put("startIndex",0);
    map.put("pageSize",2);
    List<User> list =mapper.getUserByLimit(map);
    for (User user : list) {
        System.out.println(user);
    }
    sqlSession.close();
}

9.1RowBounds分页

1.接口

List<User> getUserByRowBounds();

2.mapper.xml

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

3.测试

@Test
public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
   	RowbBounds rowbounds=new RowBounds(1,2);
    
    
    List<User> list =sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRownBounds",null,rowbounds);
    for (User user : list) {
        System.out.println(user);
    }
    sqlSession.close();
}

10.使用注解开发

1.在接口上实现

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

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

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

3.测试

@Test
public void test(){
    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();
}

本质是反射机制实现

底层是动态代理

mybatis详细的执行流程

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

10.1CRUD

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

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);//设置为true之后 就不用手动commit了
}

编写接口 增加注解

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

//方法存在多个参数  所有的参数前面必须加上@Param()注解
@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);

@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id=#{uid}")
int deleteUser(@Param("uid") int id);

测试类

 @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        List<User> users =mapper.getUsers();
//        for (User user : users) {
//            System.out.println(user);
//        }
//        User userById= mapper.getUserByID(1);
//        System.out.println(userById);

//        mapper.addUser(new User(5,"hell0","123123"));
//        mapper.updateUser(new User(5,"jack","12345"));
        mapper.deleteUser(5);
        sqlSession.close();
    }

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以省略,
  • 在SQL中引用的就是这里的@Param()中设定的属性名

9.Lombok

使用步骤:

  1. 在IDEA中安装Lombok插件

  2. 在项目中导入lombok的jar包

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>
@Data 
@AllArgsConstructor  有参构造
@NoArgsConstructor   无参构造
@ToString
@EqualsAndHashCode
@Getter
//实体类
public class User {
    private int id;
    private String name;
    private String password;
}

10.多对一 mybatis-05

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=utf8INSERT 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
  3. 建立Mapper接口
  4. 建立Mapper.xml
  5. 在核心配置文件中注册绑定我们的Mapper接口或者文件
  6. 测试查询

按照查询嵌套处理

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.StudentMapper">
    
    <select id="getStudent" resultMap="StudentTeacher">
        select *
        from student
    </select>
    
    <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="getTeacher" resultType="Teacher">
        select *
        from teacher
        where id = #{id}
    </select>
</mapper>

按照结果嵌套处理

<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.一对多 mybatis-06

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

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

按照结果嵌套处理

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

    <!--    对于集合要用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>

按照查询嵌套处理

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

小结

1.关联-association

2.集合-collection

3.javaType和ofType

​ 1.javaType用来指定实体类中属性的类型

​ 2.ofType用来指定映射到List或者集合中的pojo类型 泛型中的约束类型

12.动态SQL mybatis-07

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

12.1搭建环境

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. 编写配置文件

  1. 编写实体类
  2. 编写实体类对应Mapper接口和Mapper.xml

12.2动态SQL之if语句 mybatis-07

public interface BlogMapper {

    int addBlog(Blog blog);

    List<Blog> queryBlogIF(Map map);

}
<mapper namespace="com.kuang.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into mybatis.blog(id, title, author, create_time, views)
        values (#{id}, #{title}, #{author}, #{createTime}, #{views});
    </insert>

    <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>
</mapper>
public class MyTest {
    @Test
    public void addInitBlog() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setId(IDutils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("狂神说");
        blog.setCreateTime(new Date());
        blog.setViews(999);

        blog.setId(IDutils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("狂神说ha");
        blog.setCreateTime(new Date());
        blog.setViews(9999);
        mapper.addBlog(blog);

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

    @Test
    public void testueryBlogIF() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap Map = new HashMap();
        Map.put("title","Mybatis");
        Map.put("author","狂神说");
        List<Blog> blogs = mapper.queryBlogIF(Map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
}

12.3动态SQL常用标签

where

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

choose

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

set

<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.4SQL片段

1.在sql标签抽取公共部分

<sql id="if-title-author">
    <if test="title!=null">
        and 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标签 回对sql语句进行优化

foreach

<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>
@Test
    public void testqueryBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(1);
        map.put("ids",ids);

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

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

先去验证sql语句 然后再去拼接

13.缓存

  1. 存在内存中的临时数据
  2. 将用户查询的数据方法缓存中,用户去查询数据就不用从磁盘上读取,从缓存上查询,从而提高查询效率,解决了高并发系统的性能问题

为什么使用缓存

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

什么样的数据能使用缓存

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

13.1mybatis缓存

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

LRU:最近最少使用,移除最长时间不被使用的对象

FIFO:先进先出:按对象进入缓存的顺序来移除它们

SOFT:软引用:基于垃圾回收器状态和软引用规则移除对象

WEAK:弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象

默认的清楚策略是LRU

13.2一级缓存

1.开启日志

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

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

3.查看日志输出

缓存失效的情况

  1. 增删改操作,可能会改变原来的数据,所以说会刷新缓存
  2. 查询不同的东西
  3. 查询不同的Mapper.xml
  4. 手动清理缓存

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

13.3二级缓存

开启二级缓存只需要在.xml文件的最上方,写上即可

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

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

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

小结:

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

13.4mybatis的缓存原理

缓存顺序:第一次查询走数据库,然后放在一级缓存中

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值