# Unit01-初识Mybatis
Mybatis 文档 mybatis – MyBatis 3 | 入门
一、简介
1. 什么是Mybatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis。
- 2013年11月迁移到Github。
2. 如何获得Mybatis
- maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
- Github: Releases · mybatis/mybatis-3 · GitHub
3. 持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转换的过程。
- 内存:断电即失
- 数据库(jdbc),io文件持久化
为什么要持久化?
- 有一些对象,不可丢失
- 内存太贵了
4. 持久层
- Dao层,Service层,Controller层···
- 完成持久化工作的代码块
- 层界限十分明显
5. 特点
- 简单易学
- 灵活
- 解除sql与程序代码的耦合
- 提供映射标签,支持对象与数据库的orm字段关系映射。
- 提供对象关系映射标签,支持对象关系组建维护。
- 提供xml标签,支持编写动态sql。
# Unit02-Mybatis程序
思路:搭建环境——>导入Mybatis——>编写代码——>测试
一、搭建环境
搭建数据库
CREATE DATABASE `Mybalits`;
USE `Mybalits`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL
)ENGINE = INNODB DEFAULT CHARSET=UTF8;
INSERT INTO `user` (`id`,`name`,`password`)
VALUE(1,'张三','123456'),(2,'李四','111111'),(3,'王五','222222')
新建项目
- 新建一个普通的maven项目
- 删除src目录
- 导入maven依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
二、创建模块
- 从 XML 中构建 SqlSessionFactory
<?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"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8"/>
<property name="username" value="root"/>
<property name="password" value="cpx147258"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在mappers中注册 -->
<mappers>
<mapper resource="com/taiyuan/dao/UserDaoMapper.xml"/>
</mappers>
</configuration>
- 编写mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
InputStream inputStream = null;
try {
//获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
private static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
三、编写程序
- 实体类
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
- Dao接口
public interface UserDao {
List<User> getUserList();
}
- 接口实现类由原来的UserDaoImp变为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">
<!--namespace:命名空间,指定一个Dao接口或Mapper接口-->
<mapper namespace="com.taiyuan.dao.UserDao">
<select id="getUserList" resultType="com.taiyuan.pojo.User">
select * from mybatis.user
</select>
</mapper>
四、测试
public class UserDaoTest {
@Test
public void test(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> listUser = mapper.getUserList();
for(User user : listUser) {
System.out.println(user);
}
sqlSession.close();
}
}
# Unit03-MybatisCRUD
一、CRUD
1、namespace
namespace 中的包名要和 Dao/Mapper接口的包名一致
2、select
选择、查询语句
- id,就是对应的namespace重点的方法名
- resultType,sql语句执行的返回值
- parameterType,参数类型
编写接口
//查询全部晕乎
List<User> getUserList();
//根据id 查询用户
User getUserByid(int id);
实现Mapper中的sql
<select id="getUserList" resultType="com.taiyuan.pojo.User">
select * from mybatis.user
</select>
<select id="getUserByid" parameterType="int" resultType="com.taiyuan.pojo.User">
select * from mybatis.user where id = #{id};
</select>
测试
@Test
public void test(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> listUser = mapper.getUserList();
for(User user : listUser) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserByid(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByid = mapper.getUserByid(1);
System.out.println(userByid);
sqlSession.close();
}
3、 insert
<insert id="addUser" parameterType="com.taiyuan.pojo.User" >
insert into mybatis.user (id,name,password)values(#{id},#{name},#{password})
</insert>
4、update
<update id="updateUser" parameterType="com.taiyuan.pojo.User">
update mybatis.user set name=#{name},password=#{password} where id = #{id}
</update>
5、delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
注意点:增删改需要提交事务
sqlSession.commit();
二、万能Map
假设,我们的实体类或者数据库中的类、字段或者参数过多,我们考虑使用Map
编写接口
int addUser2(Map<Object, Object> map);
实现Mapper中的sql
<insert id="addUser2" parameterType="map" >
insert into mybatis.user (id,name,password)values(#{userid},#{username},#{password})
</insert>
测试
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("userid",5);
map.put("username","小天");
map.put("password","120120");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
三、模糊查询
- java 代码执行的时候,传递通配符% %
select * from mybatis.user where name like #{value}
- 在sql 拼接中使用通配符!
select * from mybatis.user where name like "%" #{value}"%"
编写接口
List<User> getUserLike(String s);
实现Mapper中的sql
<select id="getUserLike" resultType="com.taiyuan.pojo.User">
select * from mybatis.user where name like #{value}
</select>
测试
@Test
public void getuserlike(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("%李%");
for(User user : userLike){
System.out.println(user);
}
sqlSession.close();
}
# Unit04-Mybatis配置解析
一、配置解析
1、核心配置文件
- mybatis-config-xml
- MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
2、环境配置(environments)
MyBatis 可以配置成适应多种环境,
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
事务管理器(transactionManager)
- JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
- MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。
POOLED:连接池
3、属性(properties)
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
编写一个配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8
username=root
password=cpx147258
在核心配置文件中引入
<!--引入外部配置文件-->
<!-- <properties resource="do.properties"/>-->
<properties resource="do.properties">
<property name="username" value="root"/>
<property name="password" value="cpx147258"/>
</properties>
- 可以直接引入外部文件
- 可以在其中添加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件!
4、类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字,它仅用于 XML 配置。
- 意在降低冗余的全限定类名书写
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<typeAlias alias="Blog" type="domain.blog.Blog"/>
<typeAlias alias="Comment" type="domain.blog.Comment"/>
<typeAlias alias="Post" type="domain.blog.Post"/>
<typeAlias alias="Section" type="domain.blog.Section"/>
<typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean.
扫描实体类的包,它的默认别名就为这个类的 类名,首字母小写。
<typeAliases>
<package name="domain.blog"/>
</typeAliases>
在实体类比较少时,使用第一种方式。
在实体类比较多时,使用第二种方式。
第一种可以DIY别名,第二种则不行,如果非要改,需要在实体上添加注解。
5、设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
6、其它配置
typeHandlers(类型处理器)
objectFactory(对象工厂)
[plugins(插件)
- mybatis-generator-core
- mybatis-plue
- 通用mapper
7、映射器(mappers)
MapperRegistry, 注册绑定我们的Mapper文件。
方式一:【推荐】
<mappers>
<mapper resource="com/taiyuan/dao/UserDaoMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.taiyuan.dao.UserDaoMapperzhu"/>
</mappers>zhu
方式三:使用扫描包进行绑定
<mappers>
<package name="com.taiyuan.dao"/>
</mappers>zhu
方式二、三注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的mapper 配置文件必须在同一个报下!
8、生命周期和作用域
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
- 创建后便不在需要,局部变量
SqlSessionFactory
- 可以想象为:数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- SqlSessionFactory 的最佳作用域是应用作用域。
- 最简单的就是使用单例模式或者静态单例模式
SqlSession
- 连接到连接池的一个请求!
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭,否则资源被占用!
# Unit05-Mybatis解决属性名和字段名不一致的问题
一、问题
数据库中的字段
com.taiyuan.pojo
出现问题:
二、解决方式(resultMap)
- 起别名
<!--select * from mybatis.user where id = #{id};-->
<!--select id,name,password from mybatis.user where id = #{id};-->
<!--select id,name,password as psw from mybatis.user where id = #{id};-->
resultMap
<mapper namespace="com.taiyuan.dao.UserMapper">
<!--resultMap : 结果集映射-->
<resultMap id="UserMap" type="User">
<!--column:数据库中的字段,property:实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="psw"/>
</resultMap>
<select id="getUserByid" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id = #{id};
</select>
</mapper>
# Unit06-Mybatis日志工厂
一、日志
1、日志工厂
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手。
曾经:sout, debug
现在:日志工厂
- SLF4J
- LOG4J【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】
- NO_LOGGING
在Mybatis中具体使用那个日志实现,在设置中设定!
STDOUT_LOGGING 标准日志输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2、Log4j
什么是Log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
先导入Log4j的包
<!-- 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.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/shun.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
配置日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单使用
- 在要使用log4j的类中,导入包import org.apache.log4j.Logger;
- 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 日志级别
logger.info("info:进入了testlog4j");
logger.debug("debug:进入了testlog4j");
logger.error("error:进入了testlog4j");
# Unit07-Mybatis分页
一、使用Limit分页
select * from user limit startIndex,pageSize;
使用Mybatis实现分页,核心SQL
- 接口
List<User> getUserByLimit(Map<Object,Object> map);
- Mapper.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
- 测试
@Test
public void testLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> user = mapper.getUserByLimit(map);
for(User userlimit :user){
System.out.println(userlimit);
}
sqlSession.close();
}
二、RowBounds分页
不在使用SQL实现分页
- 测试
三、分页插件
# Unit08-Mybatis注解开发
一、注解开发
- 注解在接口上实现
public interface UserMapper {
@Select("select * from user")
List<User> getUserList();
}
- 需要在核心配置文件上绑定
<!--绑定接口 -->
<mappers>
<mapper class="com.taiyuan.dao.UserMapper"/>
</mappers>
- 测试
@Test
public void testUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
二、CRUD
查询用户
// 方法存在多个基本数据类型参数,每个参数必须加上@param
@Select("select * from user where id = #{id} and name = #{name}")
User getUserByid(@Param("id")int id,@Param("name") String name);
添加用户
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);//在工具类中可以自动提交事务
}
@Insert("insert into user(id,name,password) values(#{id},#{name},#{psw})")
int addUser(User user);
修改用户
@Update("update user set name = #{name},password = #{psw} where id = #{id}")
int updateUser(User user);
删除用户
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
三、@Param()注解
- 基本数据类型或者String类型,需要加上。
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议加上
- 我们在SQL中引用的就是我们这里的@Param()中设定的属性名!
四、mybatis详细执行过程
# Unit09-MybatisLombok
一、使用步骤
- 在IDEA中安装Lombok插件
- 导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
- 在实体类中加入注解
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
Lombok config system
@Data:无参构造,get、set、tostring、hashcoode、equals
@AllArgsConstructor
@NoArgsConstructor
# Unit10-Mybatis多对一
一、多对一
- 多个学生——对应一个老师
- 关联… 多个学生——关联一个老师【多对一】
- 集合… 一个老师——教许多学生【一对多】
CREATE TABLE `teacher`(
`id` INT(10) NOT NULL,
`name` VARCHAR(30) NOT 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=utf8;
INSERT 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);
pojo
public class Student {
private int id;
private String name;
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
二、按照查询嵌套处理
- 接口
//获取所有人
public List<Student> getStudent();
- 编写Mapper.xml
<mapper namespace="com.taiyuan.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>
- 测试
public void testgetstudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.getStudent();
for(Student student1:student){
System.out.println(student1);
}
sqlSession.close();
}
三、按照结果嵌套处理
<mapper namespace="com.taiyuan.dao.StudentMapper">
<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>
</mapper>
# Unit11-Mybatis一对多
一、一对多
pojo
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;
}
二、按照结果嵌套处理
- 接口
//获取老师及其学生
List<Teacher> getTeacher2(@Param("tid") int id);
- 编写Mapper.xml
<mapper namespace="com.taiyuan.dao.TeacherMapper">
<select id="getTeacher2" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from teacher t ,student s
where t.id = s.tid and t.id = #{tid}
</select>
<!--集合中的泛型信息,我们通过ofType获取-->
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
二、按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent">
select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Studnet" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select * from student where tid = #{tid}
</select>
小结
- 关联:association 【多对一】
- 集合:collection【一对多】
- javaType & ofType
- javaType:用来指定实体类中属性的类型
- ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
# Unit12-Mybatis动态SQL
一、动态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 '博客作者',
`creat_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览器'
) ENGINE= INNODB DEFAULT CHARSET=utf8
pojo
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date creattime;//属性名和字段名不一致
private int views;
}
Utils
//获取UUID
private static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
二、if
- 接口
//查询博客
List<Blog> getBlog(Map map);
- Mapper.xml
<select id="getBlog" resultType="Blog" parameterType="map">
select * from Blog
<!--where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。-->
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
三、choose (when, otherwise)
<select id="getBlog2" parameterType="map" resultType="Blog">
select * from Blog
<where>
<!--我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。-->
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
四、trim (where, set)
<update 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}
</update>
所谓的动态SQL,只是在SQL层面,可执行的一个逻辑代码
五、SQL片段
有的时候,我们会将一些功能部分抽取出来,方便使用!
- 使用SQL标签抽取公共的部分
<sql id="id-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
- 在需要使用的地方使用include标签引用即可
<select id="getBlog" resultType="Blog" parameterType="map">
select * from Blog
<where>
<include refid="id-title-author"></include>
</where>
</select>
六、Foreach
# Unit13-Mybatis缓存
一、简介
什么是缓存?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存中,用户查询时不用从磁盘上查询,提高查询效率,解决了高并发系统的性能问题。
二、Mybatis缓存
- Mybatis系统默认定义了两级缓存,一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,基于namespace级别的缓存
- 为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
三、一级缓存
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 如果获取相同的数据,直接从缓存中拿,不在查询数据库。
缓存失效的情况:
- 查询不同的东西
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
- 查询不同的Mapper.xml
- 手动清理缓存
sqlSession.clearCache();
四、二级缓存(全局缓存)
步骤:
- 开启全局缓存
<setting name="cacheEnabled" value="true"/>
- 在Mapper.xml中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>
可以自定义参数
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
五、自定义缓存-ehcache
EhCache 是一个纯Java
的进程内缓存框架
,具有快速、精干等特点,
导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.2</version>
</dependency>