Mybatis
环境:
- JDK 1.8
- Mysql 5.7及以上
- maven 3.6.1
- IDEA
1.简介
1.1什么是mybatis?
- MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
- MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.2 如何获得Mybatis
- maven仓库
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
- 官方中文文档:
2.第一个Mybatis程序
2.1 搭建环境
搭建数据库
create table user(
id int(10) primary key not null auto_increment,
username varchar(20),
password varchar(20)
);
insert into user(username,password) value('lizeyu','111111'),('sunjinjin','123456');
新建项目
1.新建一个普通得maven项目
2.删除src项目
3.导入maven依赖
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<!--log4j2-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
log4j2 xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration status="WARN" monitorInterval="600">
<Appenders>
<!--这个输出控制台的配置,这里输出除了warn和error级别的信息到System.out-->
<Console name="console_out_appender" target="SYSTEM_OUT">
<!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)
优先级,即DEBUG,INFO,WARN,ERROR,
-->
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
<!-- 输出日志的格式 -->
<PatternLayout pattern="%5p [%t] %d{yyyy-MM-dd HH:mm:ss} (%F:%L) %m%n"/>
</Console>
</Appenders>
<Loggers>
<!-- 配置日志的根节点 -->
<root level="trace">
<appender-ref ref="console_out_appender"/>
</root>
<!-- 第三方日志系统 -->
<logger name="org.springframework.core" level="info"/>
<logger name="org.springframework.beans" level="info"/>
<logger name="org.springframework.context" level="info"/>
<logger name="org.springframework.web" level="info"/>
<logger name="org.jboss.netty" level="warn"/>
<logger name="org.apache.http" level="warn"/>
</Loggers>
</Configuration>
2.2 创建一个模块
- 编写mybatis的核心配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--定义的别名-->
<typeAliases>
<package name="com.microsoft.pojo"/>
</typeAliases>
<!--整合JDBC-->
<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?useSSl=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<!--整合Mapper的配置文件-->
<mappers>
<mapper resource = "com/microsoft/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- 编写mybatis的工具类
//SqlSessionFactory-->SqlSession
public class MybatisUtil {
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 命令所需的所有方法。
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
2.3 编写代码
- 实体类
@Data
public class User {
private int id;
private String username;
private String password;
}
- Mapper接口
public interface UserMapper {
public List<User> selectUser();
}
- 接口实现类由原来的Impl转变为一个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">
<!--namespace绑定一个对应的Mapper接口-->
<mapper namespace="com.microsoft.mapper.UserMapper">
<select id="selectUser" resultType="User">
select * from mybatis.user;
</select>
</mapper>
2.4 测试
注意点:
org.apache.ibatis.binding.BindingException:
mybatis-config.xml添加
<mappers>
<mapper class="com.microsoft.mapper.UserMapper"/>
</mappers>
maven由于他的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案
java.lang.ExceptionInInitializerError
maven配置文件pom.xml中添加
<!--maven静态资源管理问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- junit测试
@Test
public void test() {
Logger logger = LogManager.getLogger();
//第一步:获取sqlSession对象
SqlSession sqlSession = MybatisUtil.getSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.selectUser();
//遍历
for (User user : userList) {
logger.info(user);
}
sqlSession.close();
}
3.CRUD
3.1 select
查询语句
- id:就是对应的namesapce中的方法名;
- resultType:Sql语句执行的返回值;
- parameterType:参数类型;
3.2 增删改
增删改需要提交事务
sqlSession.commit();
3.3 万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
<update id="updateUser" parameterType="map">
update mybatis.user set username = #{name} where id = #{userId};
</update>
@Test
public void test() {
Logger logger = LogManager.getLogger();
//第一步:获取sqlSession对象
SqlSession sqlSession = MybatisUtil.getSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userId", 2);
map.put("name" , "xiaoxue");
userMapper.updateUser(map);
sqlSession.commit();
sqlSession.close();
}
4. 配置解析
4.1 核心配置文件
- mybatis-config.xml
- Mybatis的配置文件包含了会影响Mybatis行为的设置和属性信息
configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
4.2 环境配置
Mybatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境
Mybatis默认事务管理器就是JDBC(还有MANAGE),连接池:POOLED
4.3 属性(properties)
这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。
db.properties
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username = root
password = 111111
需放在userMapper.xml的最顶端
<!--引入外部配置文件-->
<properties resource="db.properties"/>
4.4 类型别名
- 类型别名是为 Java 类型设置一个短的名字;
- 存在的意义仅在于用来减少类完全限定名的冗余;
<!--定义的别名-->
<typeAliases>
<package name="com.microsoft.pojo"/>
</typeAliases>
每一个在包com.microsoft.pojo 中的 Java Bean
,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为author;若有注解,则别名为其注解值。
这是一些为常见的 Java 类型内建的相应的类型别名。它们都是不区分大小写的,注意对基本类型名称重复采取的特殊命名风格。
别名 | 映射的类型 |
---|---|
_byte | byte |
_long | long |
_short | short |
_int | int |
_integer | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
integer | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
bigdecimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
iterator | Iterator |
4.5 设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项的意图、默认值等。
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存。 | true | false | true |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 | true | false | false |
useGeneratedKeys | 允许 JDBC 支持自动生成主键,需要驱动支持。 如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能支持但仍可正常工作(比如 Derby)。 | true | false | False |
mapUnderscoreToCamelCase | 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 | true | false | False |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 STDOUT_LOGGING | 未设置 |
4.6 插件(plugins)
- mybatis-generator-core MyBatis Generator-MyBatis的代码生成器。
- mybatis -plusMybatis的增强工具包,可简化开发。 文档
- 通用Mapper
4.7 映射器(mappers)
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要定义 SQL 映射语句了。 但是首先我们需要告诉 MyBatis 到哪里去找到这些语句。 Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource = "com/microsoft/mapper/UserMapper.xml"/>
</mappers>
推荐此类方式
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="com.microsoft.mapper.UserMapper"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名;
- 接口和他的Mapper配置文件必须在同一个包下;
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="com.microsoft.mapper"/>
</mappers>
注意点同上
4.8 作用域(Scope)和生命周期
理解我们目前已经讨论过的不同作用域和生命周期类是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
- 一旦创建了 SqlSessionFactory,就不再需要它了;
- 局部方法变量;
SqlSessionFactory
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例;
- 因此 SqlSessionFactory 的最佳作用域是应用作用域;
- 最简单的就是使用单例模式或者静态单例模式;
SqlSession
- 连接到连接池的一个请求;
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域;
- 用完之后立即关闭,释放资源;
5. 解决属性名和字段名不一致的问题
解决方法:
- 起别名:Sql检索起别名
5.2 resultMap
结果集映射
数据库中:id username password
实体类中:id name password
resultMap
元素是 MyBatis 中最重要最强大的元素。- ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
<!--结果集映射-->
<resultMap id="userMap" type="User">
<!--column:数据库中的字段,property:实体类中的属性-->
<result column="id" property="id"/>
<result column="username" property="name"/>
<result column="password" property="password"/>
</resultMap>
<select id="selectUser" resultMap="userMap">
select * from mybatis.user where id = #{id};
</select>
6. 日志
6.1 日志工厂
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
- SLF4J
- LOG4J
- LOG4J2【掌握】
- STDOUT_LOGGING【掌握】
在Mybatis中具体使用哪一个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis-config.xml文件中配置我们的日志
<!--设置,必须在properties,typeAliases中间-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2 log4j2
- 导包
<!--log4j2-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.10.0</version>
</dependency>
- 配置文件log4j2.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration status="WARN" monitorInterval="600">
<Appenders>
<!--这个输出控制台的配置,这里输出除了warn和error级别的信息到System.out-->
<Console name="console_out_appender" target="SYSTEM_OUT">
<!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)
优先级,即DEBUG,INFO,WARN,ERROR,
-->
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
<!-- 输出日志的格式 -->
<PatternLayout pattern="%5p [%t] %d{yyyy-MM-dd HH:mm:ss} (%F:%L) %m%n"/>
</Console>
</Appenders>
<Loggers>
<!-- 配置日志的根节点 -->
<root level="trace">
<appender-ref ref="console_out_appender"/>
</root>
<!-- 第三方日志系统 -->
<logger name="org.springframework.core" level="info"/>
<logger name="org.springframework.beans" level="info"/>
<logger name="org.springframework.context" level="info"/>
<logger name="org.springframework.web" level="info"/>
<logger name="org.jboss.netty" level="warn"/>
<logger name="org.apache.http" level="warn"/>
</Loggers>
</Configuration>
7. 分页
为什么要分页?
- 减少数据的处理
7.1 使用Limit实现
语法:select * from user limit startIndex,pagesize;
select * from user limit 1,2;
- 使用Mybatis实现分页,核心SQL
- 编写接口
public List<User> selectUserByLimit(Map<String,Object> map);
- 编写userMapper.xml中查询语句
<select id="selectUserByLimit" parameterType="map" resultMap="userMap">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
- 测试
@Test
public void getUserByLimit() {
Logger logger = LogManager.getLogger();
SqlSession sqlSession = MybatisUtil.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("startIndex",0);
map.put("pageSize",1);
List<User> userList = userMapper.selectUserByLimit(map);
for (User user : userList) {
logger.info(user);
}
sqlSession.close();
}
7.2 分页插件
8. 使用注解开发
使用注解来映射简单语句会使代码显得更加简洁,然而对于稍微复杂一点的语句,Java 注解就力不从心了,并且会显得更加混乱。 因此,如果你需要完成很复杂的事情,那么最好使用 XML 来映射语句。
本质主要应用反射
底层应用动态代理
- 接口
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
}
- 整合Mapper
<!--绑定接口-->
<mappers>
<mapper class="com.microsoft.mapper.UserMapper"/>
</mappers>
- 测试
@Test
public void test() {
Logger logger = LogManager.getLogger(UserMapperTest.class);
SqlSession sqlSession = MybatisUtil.getSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUsers();
for (User user : userList) {
logger.info(user);
}
sqlSession.close();
}
8.1 CRUD
@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 values(#{id},#{username},#{password})")
int insertUser(User user);
自动提交事务
public static SqlSession getSession() {
return sqlSessionFactory.openSession(true);
}
关于@Param()
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要机上
- 如果只有一个基本类型的话,可以忽略,但建议加上
- 我们在SQL中引用的就是我们这里的==@Param()==中设定的属性名
#{}; ${};区别
- 前者是预编译,后者是普通的
- 前者防止SQL注入
9. Lombok插件
- idea安装lombok插件
- 导入jar包
注解大全
@Data:无参构造,get,set,tostring,equals
@AllArgsConstructo:有参构造
@NoArgsConstructor:无参构造
10. 多对一
10.1 测试环境搭建
- 导入lombok
- 新建实体类 Teacher,Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件
- 测试查询是否能够成功
实体类
@Data
public class Student {
private int id;
private String username;
private Teacher teacher;
}
@Data
public class Teacher {
private int tid;
private String tname;
}
10.2 按照查询嵌套处理
<!--
思路:
1. 查询所有的学生信息
2. 根据查询出来的学生的tid,查找出来对应的老师
-->
<select id="getStudents" resultMap="stu_tea">
select * from student;
</select>
<resultMap id="stu_tea" type="Student">
<result property="id" column="id"/>
<result property="username" column="username"/>
<!--复杂的属性需要单独处理
对象: association
集合: collection
-->
<association property="teacher" column="teacher" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where t_id = #{tid}
</select>
10.3 按照结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getStudents2" resultMap="stu_tea2">
SELECT student.id,student.username,teacher.t_name FROM student INNER JOIN teacher ON student.t_id = teacher.t_id
</select>
<resultMap id="stu_tea2" type="Student">
<result property="id" column="id"/>
<result property="username" column="username"/>
<association property="teacher" javaType="Teacher">
<result property="tname" column="t_name"/>
</association>
</resultMap>
回顾一下Mysql的多对一查询
- 子查询
- 联表查询
11. 一对多
实体类
@Data
public class Student {
private int id;
private String username;
private int tid;
}
@Data
public class Teacher {
private int tid;
private String tname;
private List<Student> students;
}
11.1 按结果集查询
<select id="getTeacher" resultMap="tea_stu">
SELECT teacher.t_name,teacher.t_id,student.username,student.id FROM student
INNER JOIN teacher ON student.t_id = teacher.t_id WHERE teacher.t_id = #{tid}
</select>
<resultMap id="tea_stu" type="Teacher">
<result property="tname" column="t_name"/>
<result property="tid" column="t_id"/>
<!--集合中的泛型,使用ofType获取-->
<collection property="students" ofType="Student">
<result property="username" column="username"/>
<result property="id" column="id"/>
<result property="tid" column="t_id"/>
</collection>
</resultMap>
12. 动态SQL
什么是动态Sql:动态sql就是指根据不同的条件生成不同的sql语句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
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
12.2 IF
<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>
12.3 choose, when, otherwise
有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
还是上面的例子,但是这次变为提供了“title”就按“title”查找,提供了“author”就按“author”查找的情形,若两者都没有提供,就返回所有符合条件的 BLOG(实际情况可能是由管理员按一定策略选出 BLOG 列表,而不是返回大量无意义的随机结果)
<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>
12.4 trim, where, set
mybatis动态sql中的trim标签的使用
trim标记是一个格式化的标记,可以完成set或者是where标记的功能,如下代码:
1.
select * from user
<trim prefix="WHERE" prefixoverride="AND |OR">
<if test="name != null and name.length()>0"> AND name=#{name}</if>
<if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
</trim>
//假如说name和gender的值都不为null的话打印的SQL为:select * from user where name = 'xx' and gender = 'xx'
//在红色标记的地方是不存在第一个and的,上面两个属性的意思如下:
//prefix:前缀
//prefixoverride:去掉第一个and或者是or
2、
update user
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0"> name=#{name} , </if>
<if test="gender != null and gender.length()>0"> gender=#{gender} , </if>
</trim>
//假如说name和gender的值都不为null的话打印的SQL为:update user set name='xx' , gender='xx' where id='x'
//在红色标记的地方不存在逗号,而且自动加了一个set前缀和where后缀,上面三个属性的意义如下,其中prefix意义如上:
//suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)
//suffix:后缀
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
select id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author},
</if>
</set>
where id = #{id}
</select>
12.5 SQL片段
实现代码的复用
- 使用SQL标签抽取公共的部分
<sql id="title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
- 在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<include refid="title-author"></include>
</where>
</select>
注意事项:
- 最好基于单表来定义SQL片段
- 不要存在WHERE标签
12.6 foreach
<!--
SELECT * FROM BLOG WHERE 1=1 and (id="1" or id = "2" or id = "3")
在map中存入一个集合
-->
<select id="queryBlogForEach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
@Test
public void test3() {
Logger logger = LogManager.getLogger();
SqlSession sqlSession = MybatisUtil.getSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(2);
ids.add(3);
map.put("ids" , ids);
mapper.queryBlogForEach(map);
sqlSession.close();
}
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
注意 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
13 缓存
13.1 一级缓存与二级缓存
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置,我们对 MyBatis 3 中的缓存实现进行了许多改进。
一级缓存是默认开启的,只在一次sqlsession中有效,也就是拿到连接到关闭连接这个时间段
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<!--显式开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
<cache/>
基本上就是这样。这个简单语句的效果如下:
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
- 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
提示 缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。
这些属性可以通过 cache 元素的属性来修改。比如:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
可用的清除策略有:
LRU
– 最近最少使用:移除最长时间不被使用的对象。FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
默认的清除策略是 LRU。
flushInterval(刷新间隔)属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。 默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。
size(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。
readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。 因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。
提示 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。
小结
- 只要开启了二级缓存,在同一个Mapper下就有效;
- 所有的数据都会先放在一级缓存中;
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存;
13.2 自定义缓存
导包:
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.0</version>
</dependency>
cache-ref
回想一下上一节的内容,对某一命名空间的语句,只会使用该命名空间的缓存进行缓存或刷新。 但你可能会想要在多个命名空间中共享相同的缓存配置和实例。要实现这种需求,你可以使用 cache-ref 元素来引用另一个缓存。
<cache-ref namespace="com.someone.application.data.SomeMapper"/>
至此mybatis的基础入门结束,笔者提供一个基于ssm的开发模板,以及一个ssm项目的搭建过程,供大家学习使用
地址:https://github.com/waiting-windy/SSM-Architectural