Mybatis 笔记

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)

什么是 MyBatis?

优点

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

一、 第一个Mybatis程序

程序的结构:

1、创建数据库、表和初始化数据

CREATE DATABASE `mybatis`;USE `mybatis`;CREATE TABLE `user`(`id` INT(20) NOT NULL, `name` VARCHAR(30) DEFAULT NULL,`pwd` VARCHAR(30) DEFAULT NULL,PRIMARY KEY(`id`))ENGINE=INNODB, DEFAULT CHARSET=UTF8;INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (1, '面包', '126');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (2, '盼盼', '123');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (3, '小李', '456');

2、导入依赖

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

3、编写Mybatis的核心配置文件

db.properties

# 连接设置
# 数据库驱动
driver = com.mysql.cj.jdbc.Driver
# 连接数据库的URL地址    workers ==> 数据库名
url = jdbc:mysql://localhost:3306/workers?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
# 数据库的用户名
username = root
# 数据库的密码
password =

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis 配置文件 -->
<configuration><properties resource="db.properties" /><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments></configuration>

4、编写mybatis的工具类

// SqlSessionFactory -> SqlSession
public class MyBatisUtils {private static SqlSessionFactory sqlSessionFactory;static {// 使用 Mybatis 的第一步,获取 SqlSessionFactory 对象try {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 语句。// sqlSessionFactory.openSession(true); -> 事务自动提交public static SqlSession getSqlSession(){return sqlSessionFactory.openSession(true);}}

5、编写实体类 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;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';}}

6、编写 Dao 接口

public interface UserMapper {// 查询全部用户public List<User> getUserList();// 根据ID 查询用户public User getUserById(int id);// 增加用户public int addUser(User user);// 更新用户public int updateUser(User user);// 删除用户public int deleteUser(int id);}

7、编写 Dao 接口的 xxxMapper.xml 配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace 定义一个对应的 Dao/Mapper 接口 -->
<mapper namespace="com.example.dao.UserMapper"><select id="getUserList" resultType="com.example.pojo.User">select * from mybatis.user;</select><select id="getUserById" parameterType="int" resultType="com.example.pojo.User">select * from mybatis.user where id = #{id};</select><insert id="addUser" parameterType="com.example.pojo.User">insert into mybatis.user(`id`, `name`, `pwd`) VALUES (#{id}, #{name}, #{pwd});</insert><update id="updateUser" parameterType="com.example.pojo.User">update mybatis.user set name=#{name}, pwd=#{pwd} where id=#{id};</update><delete id="deleteUser" parameterType="int">delete from mybatis.user where id=#{id};</delete>
</mapper>

8、配置 Mybatis 配置文件

mybatis-config.xml 加上 xxxMapper.xml 的注册配置

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

9、测试

public class UserDaoTest {@Testpublic void test(){SqlSession sqlSession = MyBatisUtils.getSqlSession();// 1. 方式一UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userList = mapper.getUserList();for (User user:userList){System.out.println(user.getId());System.out.println(user.getName());System.out.println(user.getPwd());}// 2. 方式二List<User> list = sqlSession.selectList("com.example.dao.UserDao.getUserList");for (User user:list){System.out.println(user.getId());System.out.println(user.getName());System.out.println(user.getPwd());}sqlSession.close();}@Testpublic void getUserById(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.getUserById(1);System.out.println(user.toString());}@Testpublic void addUser(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);int res = userMapper.addUser(new User(6, "木子", "123123"));System.out.println(res);sqlSession.commit();  // 提交事务sqlSession.close();}@Testpublic void updateUser(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);int res = userMapper.updateUser(new User(14, "木子李", "23"));System.out.println(res);sqlSession.commit();  // 提交事务sqlSession.close();}@Testpublic void deleteUser(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);int res = userMapper.deleteUser(6);System.out.println(res);sqlSession.commit();  // 提交事务sqlSession.close();}
}

10、遇到的问题

  • xml配置文件中文注释错误问题,修改 IDEA 的文件编码。
  • Maven的资源导出问题,可以在pom.xml添加一下配置:
    <build><!-- 在build中配置Resources, 来防止我们资源导出失败的问题 --><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource></resources></build>

二、 配置

配置文档的顶层结构如下(编写的时候顺序不能倒换):

  • configuration(配置)

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

1、属性(properties)

db.properties 文件

# 连接设置
# 数据库驱动
driver = com.mysql.cj.jdbc.Driver
# 连接数据库的URL地址
url = jdbc:mysql://localhost:3306/workers?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
# 数据库的用户名
username = root
# 数据库的密码
password =

在配置文件导入,就可以使用 ${属性名} 就可以回去对应的值

<properties resource="db.properties" />

2、环境配置(environments)

  • Mybatis可以配置多套环境。尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
    default=“development” 选择使用的环境。
<environments default="development">....
</environments>
  • 事务管理器的配置(比如:type=“JDBC”)。
    在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):

    • JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
    • MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。
  • 数据源的配置(比如:type=“POOLED”)。
    • driver – 这是 JDBC 驱动的 Java 类全限定名(并不是 JDBC 驱动中可能包含的数据源类)。
    • url – 这是数据库的 JDBC URL 地址。
    • username – 登录数据库的用户名。
    • password – 登录数据库的密码。
 <dataSource type="POOLED"> ... </dataSource>

3、类型别名(typeAliases)

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

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

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

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

在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。(大写也可以,但是建议用小写)
比如 com.example.pojo.User 的别名为 user;若有注解,则别名为其注解值。

4、设置(settings)

  • mapUnderscoreToCamelCase
    是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 默认值为False。
  • logImpl
    指定 MyBatis 所用日志的具体实现,未指定时将自动查找。可选值: SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING。默认未设置。

5、映射器(mappers)

方式一: 使用相对于类路径的资源引用

<!-- 使用相对于类路径的资源引用 -->
<mappers><mapper resource="com/example/dao/UserMapper.xml" />
</mappers>

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

使用class文件绑定,注意点:

  • 接口和他的 Mapper.xml 配置文件必须同名!
  • 接口和他的 Mapper.xml 配置文件必须在同一个包下!
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers><mapper resource="com.example.dao.UserMapper" />
</mappers>

方式三: 注意点与使用class文件绑定一样

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

6、 其他配置

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

三、 作用域(Scope)和生命周期

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

SqlSessionFactoryBuilder

  • 一旦创建了 SqlSessionFactory,就不再需要它了。
  • 局部变量

SqlSessionFactory

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

SqlSession

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

四、结果集映射 (resultMap)

resultMap 元素是 MyBatis 中最重要最强大的元素。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
ResultMap 的优秀之处——你完全可以不用显式地配置它们。(属性名和字段名一致的话不需要显示配置。如下例的 xml <result column="id" property="id" />不需要配置)

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

  • column ==> 数据库的字段名。
  • property ==> pojo 实体类的属性名。
<!-- 结果集映射 -->
<resultMap id="UserMap" type="User"><result column="id" property="id" /><result column="name" property="name" /><result column="pwd" property="password" />
</resultMap>

五、日志

如果一个数据库操作,出现异常,我们需要排错,最好的助手就是日志。

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

1、STDOUT_LOGGING 标准日志输出

配置文件配置

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

直接运行程序可以在控制台看到日志输出

2、LOG4J

什么是log4j?

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

导入依赖

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

配置log4j为日志的实现

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

配置文件示例: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/pan.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

直接测试运行,可以在控制台看到日志输出,以及生成的日志文件。

如果要输出的日志的类中加入相关语句,需要定义属性(参数为当前类的class):

Logger logger = Logger.getLogger(xxx.class);

然后就可以使用添加日志级别:

    @Testpublic void testLog4j(){logger.debug("debug:进入");logger.info("info: 进入");logger.error("error: 进入");}

六、分页

1、使用 Limit 分页:

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

1、接口

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

2、mapper.xml配置

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

3、测试

    @Testpublic void getUserByLimit(){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> userByLimit = mapper.getUserByLimit(map);for (User user : userByLimit) {System.out.println(user.toString());}sqlSession.close();}

2、RowBounds分页

少用。

3、PageHelper

https://pagehelper.github.io/

七、使用注解开发

映射的语句可以不用 XML 来配置,而可以使用 Java 注解来配置。

public interface UserMapper {// 根据ID 查询用户@Select("select * from mybatis.user where id = #{id}")public User getUserById(int id);
}

映射器只能使用类绑定

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

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。

因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

八、Mybatis 的执行流程

九、复杂类型的查询

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

SQL 代码

USE mybatis;CREATE TABLE `teacher` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8INSERT 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. 新建实体类 Teacher、Student
  2. 建立 Mapper 接口
  3. 创建 Mapper.xml 文件
  4. 在核心配置文件中绑定注册 Mapper 接口
  5. 测试查询是否能够成功

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

1、多对一 【关联

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

Student:

public class Student {private int id;private String name;// 学生需要关联一个老师private Teacher teacher;// getter and setter
}

Teacher:

public class Teacher {private int id;private String name;// getter and setter
}

StudentMapper 接口

public interface TeacherMapper {//List<Teacher> getTeacher();// 获取指定老师下的所有学生及老师的信息Teacher getTeacher(@Param("tid") int id);}

StudentMapper.xml 配置文件

  • 按照查询嵌套处理
<resultMap id="StudentTeacher" type="Student"><result column="id" property="id" /><result column="name" property="name" /><!-- 复杂的属性,我们需要单独处理对象:association集合:collection--><association column="tid" property="teacher" javaType="Teacher" select="getTeacher" />
</resultMap><select id="getStudent" resultMap="StudentTeacher">select * from mybatis.student;
</select><select id="getTeacher" resultType="Teacher">select * from mybatis.teacher where id=#{id};
</select>
  • 按照结果嵌套处理
<!--  按照结果嵌套处理 -->
<select id="getStudent2" resultMap="StudentTeacher2" >select s.id sid, s.name sname, t.id tid, t.name tnamefrom mybatis.student as s, mybatis.teacher as twhere s.tid = t.id;
</select><resultMap id="StudentTeacher2" type="Student"><result column="sid" property="id" /><result column="sname" property="name" /><association property="teacher" javaType="Teacher" ><result property="id" column="tid" /><result property="name" column="tname" /></association>
</resultMap>

测试:

public class MyTest {@Testpublic void getStudent(){SqlSession sqlSession = MyBatisUtils.getSqlSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);List<Student> student = mapper.getStudent();for (Student s : student) {System.out.println(s.toString());}sqlSession.close();}@Testpublic void getStudent2(){SqlSession sqlSession = MyBatisUtils.getSqlSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);List<Student> student = mapper.getStudent2();for (Student s : student) {System.out.println(s.toString());}sqlSession.close();}}

2、 一对多 【集合

获取指定老师下的所有学生及老师的信息

Student:

public class Student {private int id;private String name;private int tid;// getter and setter
}

Teacher:

public class Teacher {private int id;private String name;// 一个老师有多个学生private List<Student> students;// getter and setter
}

TeacherMapper 接口

public interface TeacherMapper {//List<Teacher> getTeacher();// 获取指定老师下的所有学生及老师的信息Teacher getTeacher(@Param("tid") int id);}

TeacherMapper.xml 配置文件

<!-- 按照结果嵌套查询 -->
<select id="getTeacher" resultMap="TeacherStudent" >select s.id sid, s.name sname, t.name tname, t.id tidfrom mybatis.teacher t, mybatis.student swhere s.tid = t.id and t.id = #{tid};
</select><resultMap id="TeacherStudent" type="Teacher" ><result property="id" column="tid" /><result property="name" column="tname" /><!-- 集合中的泛型信息我们使用 ofType  --><collection property="students" ofType="Student" ><result property="id" column="sid" /><result property="name" column="sname" /><result property="tid" column="tid" /></collection>
</resultMap>

测试:

public class MyTest {@Testpublic void getTeacher(){SqlSession sqlSession = MyBatisUtils.getSqlSession();TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);Teacher teacher = mapper.getTeacher(1);System.out.println(teacher);sqlSession.close();}
}

小结

  • ofType : 用来指定映射到 List 或 集合中 pojo 类型,泛型中的约束类型。
  • JavaType : 用来指定实体类中属性的类型。

注意点:

  • 保证SQL的可读性。
  • 主义一对多和多对一中,属性和字段名的问题。
  • 如果问题不好排查,可以使用日志,建议使用 log4j。

十、动态 SQL

什么是动态SQL:根据不同的条件生成不同的SQL语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 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;

实体类

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

编写 mapper 接口和 mapper.xml 配置文件

public interface BlogMapper {// 插入数据int addBlog(Blog blog);// 查询博客List<Blog> queryBlogIF(Map map);// 查询id 在 1~3 号的记录List<Blog> queryBlogForEach(Map map);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.BlogMapper"><insert id="addBlog" parameterType="blog" >insert mybatis.blog(id, title, author, create_time, views)value (#{id}, #{title}, #{author}, #{createTime}, #{views});</insert><!-- 使用SQL片段,最好单表使用 --><sql id="if-title-author"><if test="title != null">title = #{title}</if><if test="author != null">AND author = #{author}</if></sql><select id="queryBlogIF" parameterType="map" resultType="blog">select * from mybatis.blog<where><include refid="if-title-author"></include></where></select><select id="queryBlogForEach" parameterType="map" resultType="blog" >select * from mybatis.blog<where>id IN<foreach collection="ids" index="index" item="id" open="(" separator="," close=")">#{id}</foreach></where></select></mapper>

测试:

public class IDUtils {public static String getId(){return UUID.randomUUID().toString().replace("-", "");}public static void main(String[] args) {System.out.println(getId());}}
public class MyTest {@Testpublic void addBlog(){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(9999);mapper.addBlog(blog);blog.setId(IDUtils.getId());blog.setTitle("Java");mapper.addBlog(blog);blog.setId(IDUtils.getId());blog.setTitle("Spring");mapper.addBlog(blog);blog.setId(IDUtils.getId());blog.setTitle("微服务");mapper.addBlog(blog);sqlSession.commit();sqlSession.close();}@Testpublic void queryBlog(){SqlSession sqlSession = MyBatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);Map<String, String> map = new HashMap<String, String>();//map.put("title", "Java");map.put("author", "狂神说");List<Blog> blogs = mapper.queryBlogIF(map);for (Blog blog : blogs) {System.out.println(blog);}sqlSession.close();}@Testpublic void queryBlogForEach(){SqlSession sqlSession = MyBatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);Map map = new HashMap();ArrayList<Integer> ids = new ArrayList<Integer>();ids.add(1);ids.add(2);ids.add(3);map.put("ids", ids);List<Blog> blogs = mapper.queryBlogForEach(map);for (Blog blog : blogs) {System.out.println(blog);}sqlSession.close();}}

choose、when、otherwise

<select id="findActiveBlogLike"resultType="Blog">SELECT * FROM BLOG WHERE state = ‘ACTIVE’<choose><when test="title != null">AND title like #{title}</when><when test="author != null and author.name != null">AND author_name like #{author.name}</when><otherwise>AND featured = 1</otherwise></choose>
</select>

foreach

<select id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST PWHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach>
</select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符。

你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。

  • 当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。
  • 当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

<where></where>标签

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

<set></set>标签

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

<update id="updateAuthorIfNecessary">update Author<set><if test="username != null">username=#{username},</if><if test="password != null">password=#{password},</if><if test="email != null">email=#{email},</if><if test="bio != null">bio=#{bio}</if></set>where id=#{id}
</update>

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

十一、缓存

1、简介

什么是缓存[Cache]?

  • 存在内存中的临时数据
  • 将用户经常查的数据放在缓存(内存)中,用户去查询数据就不用去磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决高并发系统的性能问题。
    为什么使用缓存?
  • 减少和数据库的交互次数,减少系统开销,提高系统效率
    什么样的数据能使用缓存?
  • 经常查询并且不经常改变的数据

2、Mybatis缓存

  • MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。
  • Mybatis 系统中默认定义了两级缓存: 一级缓存二级缓存
    • 默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。(SqlSession 级别的缓存,也称为本地缓存)
    • 要启用全局的二级缓存,需要手动开启和配置。(基于 namespace 级别的缓存)
    • 为了提高扩展性,Mybatis 定义了缓存接口 Cache,我们可以实现 Cache 接口来实现自定义的二级缓存

缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。

3、一级缓存

  • 一级缓存也叫本地缓存: SqlSession

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

测试:(要开启日志)

   @Testpublic void testSessionCache(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.queryUserById(1);System.out.println(user);System.out.println("=========================");User user2 = mapper.queryUserById(1);System.out.println(user2);System.out.println(user == user2);sqlSession.close();}

查看日志输出:只执行了一次SQL

缓存失效:

  1. 查询不同的数据
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存。
  3. 查询不同的Mapper.xml
  4. 手动清除缓存
sqlSession.clearCache();

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

4、 二级缓存

  • 基于namespace级别的缓存,一个命名空间,对应一个二级缓存
  • 工作机制
  • 一个会话查询一条数据,这个数据就会被存放在一级缓存中;
  • 如果当会话关闭时,这个会话的一级缓存就不存在了,一级缓存就会存到二级缓存中
  • 新的会话查询信息,就可以从二级缓存中获取内容
  • 不同的mapper查出的数据会放在自己对应的缓存(map)中

要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

<cache/>

mybatis-config.xml -> 配置文件中显示开启全局缓存(默认是开启的)

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

也可以自定义参数:

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

这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

可用的清除策略有:

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

测试:

  • 我们需要将实体类序列化(实现 Serializable 接口)
  • 两个 sqlSession 进行测试
    @Testpublic void testMapperCache(){SqlSession sqlSession1 = MyBatisUtils.getSqlSession();SqlSession sqlSession2 = MyBatisUtils.getSqlSession();UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);User user1 = mapper1.queryUserById(1);System.out.println(user1);sqlSession1.close();System.out.println("==========================");UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);User user2 = mapper2.queryUserById(1);System.out.println(user2);sqlSession2.close();}

5、 Mybatis缓存原理

6、 自定义缓存 – EhCache

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
Ehcache 是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。

导入依赖:

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.2.1</version>
</dependency>

Mapper.xml 配置使用 ehcache:

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

ehcache 的配置文件 ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="false"><!--diskStore: 为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:user.home - 用户主目录user.dir -用户当前工作目录java.io.tmpdir - 默认临时文件路径--><diskStore path="./tmpdir/Tmp_EhCache"/><defaultCacheeternal="false"maxElementsInMemory="10000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="259200"memoryStoreEvictionPolicy="LRU"/><cachename="cloud_user"eternal="false"maxElementsInMemory="5000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="1800"memoryStoreEvictionPolicy="LRU"/><!--defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使川这个缓存策略。只能定义一个。--><!--name:缓存名称。maxElementsInMemory:缓存最大数目maxElementsOnDisk:硬盘最大缓存个数。eternal:对象是否水久有效,一你设置了,timeout将不起作用。overflowToDisk;是否保存到磁盘,当系统当机时timeToIdleSeconds :设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时问和失效时问之间。仅当eternal=false利象不是永久有效时v用.默认是0..也就是对象存活时间无穷大。diskPersistent:是否缓存虚拟机重启期数据 whether the disk store persists between restarts of the virtual Machine. The default value is false.diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。memoryStoreEvictionPo1icy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFo(先进先出)或是LFU(较少使用)。clearOnFlush:内存数量最大时是否清除。memoryStoreEvictionPolicy:可选策略有:LRU〈最近最少使用,默认策略)、FIFO(先进先出)LFU(最少访问次数)。FIFo,first: in first out,这个是大家最熟的,先进先出。LFU,Less Frequently used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。LRU,Least Recent1y Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。--></ehcache>

Redis 数据库来做缓存!

Mybatis 学习笔记相关推荐

  1. mybatis学习笔记(13)-延迟加载

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(13)-延迟加载 标签: mybatis [TOC] resultMap可以实现高级映射(使用asso ...

  2. mybatis学习笔记(7)-输出映射

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(7)-输出映射 标签: mybatis [TOC] 本文主要讲解mybatis的输出映射. 输出映射有 ...

  3. mybatis学习笔记(3)-入门程序一

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(3)-入门程序一 标签: mybatis [TOC] 工程结构 在IDEA中新建了一个普通的java项 ...

  4. MyBatis多参数传递之Map方式示例——MyBatis学习笔记之十三

    前面的文章介绍了MyBatis多参数传递的注解.参数默认命名等方式,今天介绍Map的方式.仍然以前面的分页查询教师信息的方法findTeacherByPage为例(示例源代码下载地址:http://d ...

  5. ant的下载与安装——mybatis学习笔记之预备篇(一)

    看到这个标题是不是觉得有点奇怪呢--不是说mybatis学习笔记吗,怎么扯到ant了?先别急,请容我慢慢道来. mybatis是另外一个优秀的ORM框架.考虑到以后可能会用到它,遂决定提前学习,以备不 ...

  6. mybatis学习笔记--常见的错误

    原文来自:<mybatis学习笔记--常见的错误> 昨天刚学了下mybatis,用的是3.2.2的版本,在使用过程中遇到了些小问题,现总结如下,会不断更新. 1.没有在configurat ...

  7. mybatis学习笔记(1)-对原生jdbc程序中的问题总结

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(1)-对原生jdbc程序中的问题总结 标签:mybatis [TOC] 本文总结jdbc编程的一般步骤 ...

  8. MyBatis:学习笔记(4)——动态SQL

    MyBatis:学习笔记(4)--动态SQL 转载于:https://www.cnblogs.com/MrSaver/p/7453949.html

  9. Mybatis学习笔记(二) 之实现数据库的增删改查

    开发环境搭建 mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载 ...

  10. MyBatis多参数传递之混合方式——MyBatis学习笔记之十五

    在本系列文章的<MyBatis多参数传递之Map方式示例>一文中,网友mashiguang提问如下的方法如何传递参数:public List findStudents(Map condit ...

最新文章

  1. 【Elasticsearch 2.x】issues
  2. 记一次与为知笔记的客服沟通
  3. Selenium 中文API
  4. echart 高度 不用 不撑满_装修干货:橱柜高度到底要多高才合适?
  5. mysql数据库优化课程---12、mysql嵌套和链接查询(查询user表中存在的所有班级的信息?)...
  6. 机器学习--支持向量机(六)径向基核函数(RBF)详解
  7. BZOJ 2434 阿狸的打字机(ac自动机+dfs序+树状数组)
  8. Flutter自定义布局套路
  9. Python迭代器(Iterator)
  10. c语言程序设计爱心图片,c语言爱心图片表白程序源代码
  11. C语言判断素数(两种方法)
  12. leetcode第1282题
  13. Paraview源码解析8: vtkPVGlyphFilter类
  14. 五分钟GO、KEGG和COG注释和富集分析
  15. 计算机图形学 裁剪算法源代码,OpenGL计算机图形学梁友栋裁剪算法实验代码及运行结果.doc...
  16. 如何批量将图片转换成jpg格式?
  17. 并发、并行、同步、异步、进程,线程、串行、并行?一文弄懂八大概念
  18. 【BZOJ2246】【codevs2135】迷宫探险,概率DP+记忆化搜索+状态压缩+运气
  19. 一条坎坷的保研路:北理、天大、南开、厦大、川大、支保
  20. 计算机设计语言乘法符号,电脑乘法符号怎么打

热门文章

  1. 使用Axure RP实现页面跳转、弹窗显示、单选按钮、下拉框以及图片插入
  2. allegro制作通孔焊盘封装-flash热风焊盘-图文并茂的Allegro 通孔焊盘制作教程
  3. 自己计算机的网络密码,怎么知道自己宽带上网的用户名密码,我打开电脑就能直接上网。...
  4. 小程序input的type属性 text、number、idcard、digit
  5. kaggle——泰坦尼克数据集
  6. java sl4j 日志_java-slf4j日志文件保存在哪里?
  7. php下载安装方法,phpstudy 2016免费版-php开发环境下载 v2016.11.03 附带安装教程 - 安下载...
  8. C语言如何制作dIL文件,C语言怎么加循环
  9. 少儿编程网站:scratch课程如何学习和教学?
  10. 华为交换机Hybrid接口