本文根据狂神说一步步整理得到
中文官方文档
CSDN文档
MyBatis 是一个持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录
数据持久化
内存:断电即失
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
常见方式:数据库(jdbc)、IO文件持久化
持久层
Dao层、Service层、Controller层……
P16
resources
下创建 mybatis-config.xml
注意 XML 头部的声明,它用来验证 XML 文档的正确性。environment 元素体中包含了事务管理和连接池的配置。mappers 元素则包含了一组映射器(mapper),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="***********.xml"/>
mappers>
configuration>
MybatisUtils.java
通过sqlSessionFactory
为核心,创建SqlSession
对象,包含了面向数据库执行 SQL 命令所需的所有方法(读取配置文件,创建工厂)sqlSessionFactory.openSession(true);
为 true 时,自动提交事务private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 获取sqlSessionFactory 对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// SqlSession 包含了面向数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
// 自动提交事务
// sqlSessionFactory.openSession(true);
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
pojo
、接口dao
、映射文件mapper.xml
接口dao
public interface UserDao {
List<User> selectUserList();
}
映射文件mapper.xml
<mapper namespace="com.kayden.dao.UserDao">
<select id="selectUserList" resultType="com.kayden.pojo.User">
select * from user
select>
mapper>
@Test
public void test(){
// 1、获取sqlSession 对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 2、getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.selectUserList();
for (User user:userList) {
System.out.println(user);
}
//3、关闭SQLSession
sqlSession.close();
}
namespace
命名空间,用来绑定对应的Dao/Mapper接口文件
select
的使用的时候有固定的三步模板sqlSession.commit();
(可以将commit设置为true,保证自动处理事务)// 1、获取sqlSession 对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 2、getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 增删改的事务处理 sqlSession.commit();
//3、关闭SQLSession
sqlSession.close();
select
parameterType
传入参数类型
resultType
返回值类型
<select id="selectUserId" parameterType="int" resultType="com.kayden.pojo.User">
select * from mybatis.user where id = #{id};
select>
insert
<insert id="addUser" parameterType="com.kayden.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
insert>
update
<update id="updateUser" parameterType="int">
update mybatis.user set
name = #{name,jdbcType=VARCHAR},
pwd = #{pwd,jdbcType=VARCHAR},
where id = #{id};
update>
delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
delete>
分页例子
List<User> getUserByLimit(Map<String,Integer> map);
<select id="getUserByLimit" parameterType="map" resultType="com.kayden.pojo.User">
select * from mybatis.user limit #{startIndex},#{pageSize};
select>
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
% %
select * from mybatis.user where name like #{name}
List<User> userList = userMapper.getUserLike("%李%");
CONCAT
select * from mybatis.user where name like concat('%',#{name},'%')
List<User> userList = userMapper.getUserLike("李");
MyBatis官方文档-XML 配置
mybatis-config.xml
注意:在核心配置文件中的标签有着各自固定的先后顺序,改变顺序会报错
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置
db.properties
driver=com.mysql.jdbc.Driver
# 其中的 & 符号与在核心配置文件中不同,不需要额外的转义
url= jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
db.properties
<properties resource="db.properties">
properties>
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<settings>
<setting name="cacheEnabled" value="true"/>
...
settings>
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 缓存开关 | true | false | true |
lazyLoadingEnabled | 懒加载 fetchType |
true | false | false |
logImpl | 日志,未指定时将自动查找 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 |
mapUnderscoreToCamelCase | 开启驼峰命名自动映射,将数据库中的_改为驼峰命名 | SESSION | STATEMENT | SESSION |
environments & environment
尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境
每个数据库对应一个 SqlSessionFactory 实例
<environments default="development11111">
<environment id="development11111">
<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>
<environment id="development22222">
....
environment>
environments>
事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")
JDBC
- 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域数据源(dataSource)
用来连接数据库
有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")
默认就是POOLED
,有池连接,能使并发 Web 应用快速响应请求。
1、给指定实体类取别名
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<typeAliases/>
2、扫描实体类的包
在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名
<typeAliases>
<package name="com.kayden.pojo"/>
typeAliases>
扫描了包后,在返回的结果可以直接用小写的实体类名
<select id="getUserLike" resultType="user">
select * from mybatis.user where name like concat('%', #{name},'%')
select>
适用场景
在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议使用第二种。
在方法 2 的基础上使用注解
@Alias("author")
public class Author {
...
}
默认的别名
_
——基本数据类型告诉 MyBatis 到哪里去找映射文件
使用相对于类路径的资源引用**resource
(推荐)**
使用完全限定资源定位符(URL)url
使用映射器接口实现类的完全限定类名class
将包内的映射器接口实现全部注册为映射器name
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<package name="org.mybatis.builder"/>
mappers>
生命周期,和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
SqlSessionFactory
SqlSession
当两个字段一致时,mybatis的类型处理器会自动匹配
字段不一致会导致查询为 NULL
比如:实体类 password 对应数据库字段的 pwd
<select id="selectUserId" parameterType="int" resultType="com.kayden.pojo.User">
select * from user where id = #{id};
select>
as
起别名select id,name,pwd as password from user where id = #{id};
resultMap
映射
column
—— 数据库中的字段property
—— 实体类的属性名resultType
修改为resultMap
association
collection
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="selectUserId" parameterType="int" resultMap="UserMap">
select * from user where id = #{id};
select>
适用场景
复杂的 Mappers 使用方法见下文的复杂查询
SLF4J | LOG4J |STDOUT_LOGGING
需要在配置文件中配置(setting
中的内容必须正确,改大小写,加空格都会出错)
STDOUT_LOGGING
标准的日志输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
Log4j 是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUl组件。可以控制每一条日志的输出格式;
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<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/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
import org.apache.log4j.Logger;
Logger logger = Logger.getLogger(UserMapperTest.class);
logger.info("info-----");
logger.debug("debug-----");
logger.error("error-----");
用来减少数据的处理量
limit 起始值(下标从0开始),页长select * from table limit 0,2;
List<User> getUserByLimit(Map<String,Integer> map);
<select id="getUserByLimit" parameterType="map" resultType="com.kayden.pojo.User">
select * from mybatis.user limit #{startIndex},#{pageSize};
select>
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
RowBounds 分页(了解)
视频地址
PageHelper 分页
官网文档
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
使用反射实现
@Select("select * from user")
List<User> selectUserList();
<mappers>
<mapper class="mapper.UserMapper.xml"/>
mappers>
工具类实现自动提交事务sqlSessionFactory.openSession(true)
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
@Param()
如果是多参数或基本类型或String类型的时候必须加上
@Select("select * from user where id = #{ID}")
User getUserById(@Param("ID") int id);
@Insert("insert into user(id,name,pwd) values (#{id} ,#{name} ,#{pwd} )")
int addUser2(User user);
@Update("update user set name = #{name},pwd = #{pwd} where id = #{id} ")
int updateUser2(User user);
@Delete("delete from user where id = #{id} ")
int deleteUser2(@Param("id") int i);
使用resultMap
映射,官网举例
多个学生 —— 一个老师,有学生表和教师表,学生表的tid
是教师表的外键
public class Student {
private int id;
private String name;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
如果只是对 Student表 查询是无法将Teacher
的数据读出
在resultMap
中嵌套result
(效率要比子查询要高)
column
中都需要使用对应别名)resultMap
的外层result
中一一写出对应的属性和字段association
中写入对应的属性和 javaBeanresult
中是另一张表所需要的属性和字段<select id="selectStudentList02" resultMap="studentTeacher02">
select s.id as sid,s.name as sname,t.name as tname
from student s ,teacher t
where s.tid = t.id;
select>
<resultMap id="studentTeacher02" type="com.kayden.pojo.Student">
<result property="id" column="sid" />
<result property="name" column="sname"/>
<association property="teacher" javaType="com.kayden.pojo.Teacher">
<result property="name" column="tname"/>
association>
resultMap>
这里需要使用和resultMap
resultMap="studentTeacher"
resultMap
,有association
表示对象,联合所查询的教师数据
property
—— 类中的复杂属性javaType
—— 需要返回的类column
—— 在数据库中的字段(外键)select
—— 属性对象所查询出的数据(外键)association
;集合 —— collection
<resultMap id="studentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="Teacher" select="selectTeacherById" column="tid"/>
resultMap>
<select id="selectStudentList" resultMap="studentTeacher">
select * from student
select>
<select id="selectTeacherById" resultType="teacher">
select * from teacher where id = #{id};
select>
一个学生对应多个老师
public class Student {
private int id;
private String name;
private int tid;
}
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
查询一对多的 sql
select t.id tid,t.name tname,s.id sid,s.name sname
from student s,teacher t
where s.tid = t.id and t.id = 1;
resultMap
中由于是List
集合类,需要使用collection
ofType
代替javaType
来表示返回的对象集合List<Teacher> selectTeacherById(@Param("tid") int tid);
<select id="selectTeacherById" resultMap="teacherStudent" >
select t.id tid,t.name tname,s.id sid,s.name sname
from student s,teacher t
where s.tid = t.id and t.id = #{tid};
select>
<resultMap id="teacherStudent" type="com.kayden.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="com.kayden.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
collection>
resultMap>
返回值
Teacher(id=1, name=秦老师, students=[Student(id=1, name=小明, tid=0), Student(id=2, name=小红, tid=0), Student(id=3, name=小张, tid=0), Student(id=4, name=小李, tid=0), Student(id=5, name=小王, tid=0)])
一对多 子查询
总结
狂神说-Mybatis
动态SQL:指根据不同的条件生成不同的SQL语句
常用于条件搜索(有数据查数据,没数据查全部)
List<Blog> selectIf(Map map);
<select id="selectIf" parameterType="map" resultType="blog">
select * from blog where 1=1
<if test="title != null ">
and title = #{title}
if>
<if test="author != null ">
and author = #{author}
if>
select>
@Test
public void test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
hashMap.put("title","Mybatis");
hashMap.put("author","狂神说");
List<Blog> blogs = mapper.selectIf(hashMap);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
where 1=1
,and 、or
符号会被拼接,导致sql语句出错where标签
,可以设置成动态条件,会将sql中的and、or舍弃select * from blog where
<if test="title != null ">
and title = #{title}
if>
<if test="author != null ">
and author = #{author}
if>
优化
使用where标签
代替where
当where内的if语句都不匹配时,就输出全部
<select id="selectIf" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title != null ">
and title = #{title}
if>
<if test="author != null ">
and author = #{author}
if>
where>
select>
实现代码的重用
使用sql
标签抽取公共部分,在需要的地方由include
引用
<sql id="sqlUpdte" >
<if test="title != null">
title = #{title},
if>
<if test="author != null">
author = #{author},
if>
sql>
<update id="updateBlogSetsql" parameterType="map">
select * from blog
<include refid="sqlUpdte">include>
update>
相当于switch...case...otherwise
,只能优先输出符合的第一个case/otherwise
<select id="selectChoose" parameterType="map" resultType="com.kayden.pojo.Blog">
select * from blog
<where>
<choose>
<when test="title != null">
and title = #{title}
when>
<when test="author != null">
and author = #{author}
when>
<otherwise>
and views = #{views}
otherwise>
choose>
where>
select>
动态更新语句,忽略其它不更新的列
注意
,
如果省略会拼接错误,
在set标签中会自动将,
舍弃,
真正的sql语句update blog SET title = ?, author = ? where id = ?
<update id="updateBlogSet" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
if>
<if test="author != null">
author = #{author},
if>
set>
where id = #{id}
update>
HashMap hashMap = new HashMap();
hashMap.put("author","狂神说Set2");
hashMap.put("id","0e28c4546c9a4df786d99bf66f2222eb");
int i = mapper.updateBlogSet(hashMap);
foreach使用场景:对集合进行遍历(尤其是在构建 IN 条件语句的时候)
使用in
遍历
select * from mybatis.blog where id in (1,2);
<select id="selectForeach" resultType="com.kayden.pojo.Blog" parameterType="map">
select * from mybatis.blog
where id in
<foreach collection="ids" item="id" open=" (" close=")" separator=",">
id = #{id}
foreach>
select>
使用and/or拼接
select * from mybatis.blog where 1=1 and (id = 1 or id = 2);
<select id="selectForeach" resultType="com.kayden.pojo.Blog" parameterType="map">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" separator="or" close=")">
id = #{id}
foreach>
where>
select>
HashMap hashMap = new HashMap();
ArrayList<String> ids = new ArrayList<String>();
ids.add("1");
hashMap.put("ids",ids);
List<Blog> blogs = mapper.selectForeach(hashMap);
Mybatis官网-缓存
目的
减少和数据库的交互次数,减少系统开销,提高系统效率
什么样的数据适合从缓存中读取
经常查询并且不经常改变的数据。
MyBatis缓存
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
默认开启,只在一次SQLSession中有效,也就是从拿到连接到关闭连接,默认的清除策略是 LRU(最近最少使用)
测试
同一个查询在测试中只查询了一次
SQLSession.clearCache()
二级缓存也叫全局缓存,是基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
工作机制
步骤
<setting name="cacheEnabled" value="true"/>
<cache/>
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
测试代码
同一个mapper
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession02 = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
BlogMapper mapper02 = sqlSession02.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlogById(1);
System.out.println(blog);
sqlSession.close();
Blog blog2 = mapper02.selectBlogById(1);
System.out.println(blog == blog2);
sqlSession02.close();
可能存在的问题
java.io.NotSerializableException
总结
执行顺序
视频地址
纯Java的进程内缓存框架
依赖
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.0.0version>
dependency>