1、简介
1.1、什么是Mybatis
- 是一款优秀的 持久层框架
- MyBatis 是支持定制化 SQL、存储过程以及高级映射
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
- MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
可从以下链接获取帮助文档和源码:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
1.2、持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬间状态转化的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化
- 生活例子:冷藏,不用的时候冷藏起来
为什么需要持久化?
- 有一些对象,不能失去,需要“冷藏“起来
- 不使用内存“冷藏”,是因为内存昂贵
1.3、持久层
- 完成持久化工作的代码块
- 层界限明显
1.4、为什么需要Mybatis?
- 帮助程序员将数据存入到数据库中
- 方便快捷
- 传统的JDBC代码太复杂。简化,框架,自动化。
- 简单易学
- 灵活
- sql和代码分离,提高可维护性
- 提供映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
2、第一个Mybatis程序
2.1、搭建环境
思路:搭建环境 ----- 导入Mybatis ----- 编写代码
需要导入maven依赖:mysql、Mybatis、junit(这是测试依赖)
<dependencies>
<!-- Mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!-- Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
2.2、创建一个模块
设置一个xml配置文件,包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)
mybatis-config.xml 文件(配置文件):
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据库驱动 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- 连接数据库的名称,可在idea连接数据库中查看 -->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&userUnicode=true&characterEncoding=UTF-8"/>
<!-- 数据库用户名和密码 -->
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 每一个Mapper.xml都需要在Mybatis核心配置文件中注册! -->
<mappers>
<mapper resource="com/sdablog/dao/UserMapper.xml"/>
</mappers>
</configuration>
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
编写一个获取SqlSession的工具类:
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//第一步:使用Mybatis获取sqlSessionFactory对象
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
* SqlSession 提供了在数据库执行 org.apache.ibatis.jdbc.SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
* @return SqlSession
*/
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
2.3、编写代码
-
实体类(这个就不说了,和之前学的javaweb没什么区别)
-
Dao接口(接口类也没有什么变化,就是命名名称可能会发生变化)
-
接口实现类
在javaweb学习时,接口需要一个UserImpl.java的实现类,但在Mybatis中,不需要了!
可直接创建一个xml配置文件,java程序直接调用上面SqlSession的工具类获取对象就可以直接执行sql命令。这是我dao层的目录:
其中UserMapper 是接口文件
UserMapper.xml:
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace = 绑定一个对应的Dao/Mapper接口 -->
<mapper namespace="com.sdablog.dao.UserMapper">
<!-- id:接口的方法名称 resultType:方法返回的数据类型 -->
<select id="getUserList" resultType="com.sdablog.pojo.User">
<!-- 需要执行的sql语句-->
select * from mybatis.user
</select>
</mapper>
注:
如果有报错:Type interface com.sdablog.dao.UserMapper is not known to the MapperRegistry.
是配置文件(mybatis-config.xml )没有加入mappers注册:
<mappers>
<!-- 接口实现类的配置文件路径 -->
<mapper resource="com/sdablog/dao/UserMapper.xml"/>
</mappers>
resource:接口实现类的配置文件路径
tips:如果出现找不到资源的报错,需要在pom.xml文件中加入build,这样jvm编译才会吧main目录里面的资源文件编译。
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
要是上面的操作都没问题,依然报错“找不到资源”,将UserMapper.xml(接口实现类xml配置文件)的头部 encoding="UTF-8"改为encoding=“UTF8”。
2.4、测试Mybatis
public class UserMapperTest {
@Test
public void test(){
//获得sqlSeesion对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行sql
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user:userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
}
3、CRUD
3.1、namespace
namespace中的包名要和Dao/Mapper接口的包名一致
Mapper接口路径:
Mapper.xml的namespace写法:
3.2、select查询标签
查询语句:
<select id="getUserById" parameterType="int" resultType="com.sdablog.pojo.User">
select * from mybatis.user where id = #{id}
</select>
- id:对应的namespace中的方法名(就是接口类的接口方法)
- resultType:Sql语句执行的返回值类型
- parameterType:需要传入的参数类型
步骤:
- 编写接口
/**
* 根据ID查询用户
* @param id 用户id
* @return User对象
*/
User getUserById(int id);
- 编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.sdablog.pojo.User">
select * from mybatis.user where id = #{id}
</select>
- 测试
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
//关闭sqlSession的连接
sqlSession.close();
}
3.3、Insert
<insert id="addUser" parameterType="com.sdablog.pojo.User">
<!-- 对象中的属性可以直接取出来用(#{id},#{name},#{pwd})-->
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
3.4、update
<update id="updateUser" parameterType="com.sdablog.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
3.5、Delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
3.6、解决疑惑
在mapper中,对象中的属性可以直接取出来用。
<insert id="addUser" parameterType="com.sdablog.pojo.User">
<!-- 对象中的属性可以直接取出来用(#{id},#{name},#{pwd})-->
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
代码中的“ values (#{id},#{name},#{pwd} ”,用#{}可取出对象中有的属性。
这是User对象中的属性,所以可以直接用#{id}取出:
注意点:增删改需要提交事务!
例如测试类:
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper user = sqlSession.getMapper(UserMapper.class);
int i = user.addUser(new User(5, "王子", "12121212"));
System.out.println(i);
//提交事务
sqlSession.commit();
sqlSession.close();
}
3.7、万能Map
假设实体类或者数据库中的表,字段或者参数太多,可以考虑使用Map。
接口类:
// 万能Map
int addUser2(Map<String,Object> map);
Mapper类:
<insert id="addUser2" parameterType="map">
<!-- 对象中的属性可以直接取出来用 传递map的key值-->
insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{password})
</insert>
测试类:
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("userid",4);
map.put("username","java");
map.put("password","11221122");
int i = mapper.addUser2(map);
System.out.println(i);
// 插入数据记得开启事务
sqlSession.commit();
sqlSession.close();
}
对象传参 与 Map传参区别:
- Map传递参数,直接在sql中取出key即可(传参类型记得改为:parameterType=“map”)
- 对象传递参数,直接在sql中取出对象属性即可
- 只有一个基本类型参数的情况,可直接在对象中取出属性
- 多个参数是,可用Map传参,或者注解
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可以配置多种环境,但是每个SqlSeesionFactory实例只能选择一种环境。
Mybatis默认事务管理器(transactionManager)是JDBC,连接池(dataSource)是:POOLED
4.3、属性(properties)
我们可以通过properties属性来实现引用配置文件。
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
- 编写一个配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=trueuserUnicode=truecharacterEncoding=UTF-8
username=root
password=123456
在核心配置文件(mybatis-config.xml)中引入:
4.4、类别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
文件路径,以下实例用到此处的User实体类。
- 直接在xml中配置名字:
<!-- 给实体类起别名-->
<typeAliases>
<typeAlias type="com.sdablog.pojo.User" alias="ss"/>
</typeAliases>
这种 type 需要映射到具体的实体类包名。
- 通过扫描包的形式,使用实体类 类名的首字母小写为别名:
<!-- 给实体类起别名-->
<typeAliases>
<package name="com.sdablog.pojo" />
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean。扫描实体类的包,它的默认别名就是这个类的别名,首字母小写。
注:这种只需引入实体类包的父路径
- 注解起别名:
映射所需实体的类名
<!-- 给实体类起别名-->
<typeAliases>
<package name="com.sdablog.pojo"/>
</typeAliases>
实体类注解别名
@Alias("hello")
public class User {
}
这样Mapper.xml中的返回值就直接可以用你自己定义的别名了。
使用场景:
- 在实体类比较少的时候,使用第一种方式
- 实体类较多,使用第二种
4.5、映射器(mappers)
既然 MyBatis 的行为已经配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件,注册绑定我们的Mapper文件。该映射器在配置文件下添加
可以使用:
- 相对于类路径的资源引用,
- 引用类名和包名等。
- 方式一:使用文件类的相对路径(推荐)
<!-- 每一个Mapper.xml都需要在Mybatis核心配置文件中注册! -->
<mappers>
<mapper resource="com/sdablog/dao/UserMapper.xml"/>
</mappers>
- 方式二:使用class文件绑定注册
<mappers>
<mapper class="com.sdablog.dao.UserMapper"/>
</mappers>
- 方式三:将包内的映射器接口实现全部注册为映射器
<mappers>
<package name="com.sdablog.dao"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一包下
4.5、resultMap
- resultMap 元素是 MyBatis 中最重要最强大的元素
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
<mapper namespace="com.sdablog.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" resultMap="UserMap">
select * from mybatis.user where id =${id}
</select>
5、日志
5.1、日志工厂
如果一个数据库出现了异常,我们需要排错,日志就是最好的助手。
这是Mybatis提供的日志方法:
设置名 | 描述 | 有效值 |
---|---|---|
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J 、 LOG4J 、 LOG4J2 、 JDK_LOGGING 、COMMONS_LOGGING 、 STDOUT_LOGGING 、NO_LOGGING |
只需掌握:
- LOG4J
- STDOUT_LOGGING (标准日志输出)
在mybatis中 具体使用哪个日志,在设置中设定。
核心配置文件(mybatis-config.xml)中配置:
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
输出:
5.2、LOG4J
什么是LOG4J ?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件;
- 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程;
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
步骤:
- 导入LOG4J 需要的Maven包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- 建立 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.Console.encoding=UTF-8
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/L.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
- 配置log4j的实现:
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用:
- 在要使用 log4j 类中,导入 org.apache.log4j.Logger ;
- 获取log的类,把需要输出类作为参数传入:
static Logger logger = Logger.getLogger(UserTest.class);
- 日志级别:
log4j规定了默认的几个级别:ALL < trace < debug < info < warn < error < fatal < OFF
- DEBUG:调试信息:指出细粒度信息事件对调试应用程序是非常有帮助的。
- INFO: 提示信息:消息在粗粒度级别上突出强调应用程序的运行过程。
- WARN: 警告信息:表明会出现潜在错误的情形。
- ERROR:错误信息:指出虽然发生错误事件,但仍然不影响系统的继续运行。
- FATAL: 致命的错误:指出每个严重的错误事件将会导致应用程序的退出。
6、注解开发
6.1、使用注解开发
- 注解在接口上实现
@Select("select * from mybatis.user")
List<User> getListUser();
- 需要在核心配置文件绑定接口
<mappers>
<mapper class="com.sdablog.dao.UserMapper"/>
</mappers>
实现本质:反射机制
底层:动态代理
6.2、mybatis详细执行流程
暂时留空…………
6.3、CRUD
我们可以在工具类创建的时候实现自动提交事务
使用注解来操作数据库增删改查;
注意:必须在配置文件中绑定对应接口!
<mappers>
<mapper class="com.sdablog.dao.UserMapper"/>
</mappers>
接口代码(包括增删改查):
public interface UserMapper {
@Select("select * from user")
List<User> getListUser();
/**
* 根据用户id查询用户
* @param id 用户ID
* @return 用户信息
*/
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
/**
* 插入用户
* @param user 用户信息
* @return 成功的行数
*/
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);
/**
* 修改用户
* @param user 用户修改信息
* @return 成功行数
*/
@Update("update user set name = #{name},pwd=#{pwd} where id = #{id}")
int updateUser(User user);
/**
* 删除用户
* @param id 需要删除用户的id
* @return 成功的行数
*/
@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid") int id);
}
字符串替换:默认情况下,使用 #{} 参数语法时,MyBatis 会创建 PreparedStatement 参数占位符,并通过占位符安全地设置参数(就像使用 ? 一样)。
关于@Param()注解:
- 基本类型或String类型,需要加上该注解
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,建议加上
- 在SQL中引用的 #{id} 就是该注解设定的属性名
7、Lombok
7.1、什么是lombok?
看看什么是lombok:
Lombok 是一个非常神奇的 java 类库,会利用注解自动生成 java Bean 中烦人的 Getter、Setter,还能自动生成 logger、ToString、HashCode、Builder 等 java特色的函数或是符合设计模式的函数,能够让你 java Bean 更简洁,更美观。
lombok 的思想非常先进,它让我们省略繁琐的样板代码,不要在重复的代码上花费太长时间,它也是Java语言演进过程中必然出现的一种思想,要用20% 的时间做 80%的事情。
7.2、使用步骤:
- 在IDEA中安装Lombok插件
- 在项目中导入lombok依赖包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
- 在实体类上加上注解
7.3、注解 @Data
@Data 是一个很方便的注解,它和 @ToString、 @EqualAndHashCode、@Getter / @Setter、和@RequiredArgsConstructor 绑定在一起。换句话说,@Data 生成通常与简单的POJO(Plain Old Java Objects) 和 bean 相关联的所有样板代码。
@Data = @Getter + @Setter + @ToString + @EqualsAndHashCode + @RequiredArgsConstructor
注:@Data 无法设置这些注解的参数!
7.4、常用注解
8、多对一查询
回顾一下Mysql的多对一的查询方式:
- 子查询
- 连表查询
8.1、查询嵌套处理
Student实体类:
public class Student {
private int id;
private String name;
private Teacher teacher;
}
StudentMapper.xml:
<mapper namespace="com.sdablog.dao.StudentMapper">
<select id="getStudent" resultMap="studentTeacher">
select * from mybatis.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 mybatis.teacher where id = #{tid}
</select>
</mapper>
思路:
- 查询所有的学生
- 根据查询出来的学生id,寻找对应的老师
property 值为实体类中对象的值(这里为student实体类中的teacher属性),column 为两表关联id(指该属性在数据库中对应的列名),javaType 为对应的实体类,select 为多方查询语句的命名id(需要连表查询的select语句的id名称)
8.2、结果嵌套处理
StudentMapper.xml:
<select id="getStudent2" resultMap="studentTeacher2">
select s.id sid, s.name sname, t.name tname
from mybatis.teacher t, mybatis.student s
where t.id = s.tid
</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>
8.3、集合嵌套查询
<mapper namespace="com.sdablog.dao.TeacherMapper">
<select id="getTeacher" resultMap="StudentTeacher">
select s.id sid, s.name sname, t.name tname, t.id tid
from mybatis.teacher t, mybatis.student s
where t.id = s.tid and tid = #{tid}
</select>
<resultMap id="StudentTeacher" 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>
</mapper>
集合用 collection ,集合中的泛型信息,使用ofType获取。
8.4、小结
- 关联 - association (场景:多对一)
- 集合 - collection (场景:一对多)
- javaType & ofType
- javaType:指实体类中属性的类型
- ofType:映射到list集合属性中pojo的类型
9、动态SQL
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
本质还是SQL语句,只是在SQL层面进行的一个逻辑代码。
动态SQL元素 和 XML的文本处理器相似,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
9.1、if
<select id="queryBlogIf" parameterType="com.sdablog.pojo.Blog" resultType="blog">
select * from mybatis.blog where title = #{title}
<if test="author != null">
and author = #{author}
</if>
</select>
9.2、choose (when、otherwise)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情
况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
choose :
<select id="queryBlogIf" parameterType="com.sdablog.pojo.Blog" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
</choose>
</where>
</select>
9.3、trim、where、set
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句
的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
where:
<select id="queryBlogIf" parameterType="com.sdablog.pojo.Blog" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
author = #{author}
</if>
</where>
</select>
等于sql语句:
select * from mybatis.blog where title = #{title} and author = #{author}
set:
set 元素会动态地在行首插入 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>
注:set语句里的逗号需要加上,mybatis在执行时会自动判断你的逗号是否需要删除。
9.3、SQL片段
有时候,我们需要把公共的SQL抽取出来,方便使用。
- 使用sql标签抽取公共部分
<sql id="if-queryBlogIf">
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
</choose>
</sql>
- 在需要使用这段sql的地方用include标签引用
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-queryBlogIf"/>
</where>
</select>
注意事项:
3. 最好基于单表来定义SQL片段
4. 不要存在where标签
9.4、foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。
blog数据库表:
foreach元素:
元素 | 描述 | 可选项 |
---|---|---|
collection | 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param(“keyName”)来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = “ids”.如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = “ids.id” | 必选 |
item | 集合中元素迭代时的别名 | 可选 |
index | 在list和数组中,index是元素的序号,在map中,index是元素的key | 可选 |
open | foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时 | 可选 |
separator | 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样 | 可选 |
close | foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时 | 可选 |
原sql语句:
select * from blog where 1=1 and (id=1 or id=2)
foreach语句的sql:
<select id="queryBlogForeache" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id= #{id}
</foreach>
</where>
</select>
测试:
public void queryBlogForeache(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<Object, Object> map = new HashMap<>();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
map.put("ids", ids);
List<Blog> blogs = mapper.queryBlogForeache(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL就是在拼接sql语句,我们只要保证sql的正确性,安装sql的格式,去排列组合就行。
10、缓存
10.1、缓存简介
-
什么是缓存?
- 存在内存中的临时数据。
- 将用户经常查询的数据存放(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率解决高并发系统的性能问题
-
为什么使用缓存?
- 减少和数据库交流的次数,减少系统开销,提高系统效率。
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
10.2、Mybais缓存
- mybatis缓存包含一个非常强大的缓存特性,可以方便的定制和配置缓存。缓存可以极大提升查询效率。
- mybatis中默认定义了两级缓存:一级缓存、二级缓存
- 默认情况下,只有一级缓存开启。(sqlsession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,mybatis定义了缓存接口Cache,我们可以通过Cache接口来定义二级缓存
10.3、一级缓存
一级缓存也叫本地缓存。
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同数据,直接从缓存中拿,没必要去查询数据库
10.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低,所以诞生了二级缓存
- 基于namespace级别缓存,一个名称空间,对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会有关闭,这个会有对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤:
- 在配置文件(mybatis-config.xml)中开启缓存:
<!-- 显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的mapper中开启
<mapper namespace="com.sdablog.dao.BlogMapper">
<!-- 在当前mapper.xml开启缓存-->
<cache/>
</mapper>
也可以在开启缓存的时候自定义参数:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
Cache标签有六个参数:
参数名 | 说明 |
---|---|
type | 指定缓存(cache)接口的实现类型,当需要和ehcache整合时更改该参数值即可。 |
flushInterval | 刷新间隔。可被设置为任意的正整数,单位毫秒。默认不设置。 |
size | 引用数目。可被设置为任意正整数,缓存的对象数目等于运行环境的可用内存资源数目。默认是1024。 |
readOnly | 只读,true或false。只读的缓存会给所有的调用者返回缓存对象的相同实例。默认是false。 |
eviction | 缓存收回策略。LRU(最近最少使用的),FIFO(先进先出),SOFT( 软引用),WEAK( 弱引用)。默认是 LRU。 |
eviction 的缓存策略:
- LRU: 最近最少使用的,移除最长时间都没有被使用的对象;
- FIFO:先进先出,移除最先进入缓存的对象;
- SOFT:软引用,移除基于垃圾回收器状态和软引用规则的对象。
- WEAK:弱引用,更积极的移除基于垃圾收集器状态和若引用规则的对象
小结:
- 只有开启了二级缓存,在同一个mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交或者关闭的时候,才会提交到二级缓存中