Maven 配置
Mybatis
1 、简介
1.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
如何获得Mybatis?
-
maven仓库
<!-- 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 持久层
Dao层、Service层、Controller层…
-
完成持久化工作的代码块
-
层界限明显
1.4 为什么需要Mybatis
- 方便
- 传统的JDBC代码太复杂
- 将数据存入到数据库中
- 优点:
- 简单易学
- 灵活
- sql和代码分离,提高可维护性
- 提供映射标签,支持对象与数据库的orm(对象关系映射)字段关系映射
- 提供对象关系映射标签,支持对象关系组件维护
- 提供xml标签,支持编写动态sql
2、First Mybatis Project
【思路】:搭建环境 ——> 导入Mybatis——>编写代码——>测试
2.1 环境搭建
2.1.1搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20)PRIMARY KEY,
`name` VARCHAR(30)DEFAULT NULL,
`pwd` VARCHAR(30)DEFAULT NULL
)ENGINE=INNODB;
INSERT INTO `user`(`id`,`name`,`pwd`)VALUES
(1,'grandpa','123456'),
(2,'thc','123456')
2.1.2 IDEA 新建项目
1、新建一个普通的Maven项目 并配置好设置(Settings–>Maven)
2、删除src目录
3、导入maven依赖【pom.xml】
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/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.12</version>
</dependency>
</dependencies>
<!-- 在build中配置resources ,放置资源导出失败的问题-->
<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>
2.2 创建一个模块
- 新建Module
-
在pom.xml中加入配置resources
<!-- 在build中配置resources ,放置资源导出失败的问题--> <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>
-
编写mybatis的核心配置文件**(放在src-main-resources下 mybatis-config.xml文件)**
-
【每一个mappers都需要在配置文件中注册】
<?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> <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=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="dao/UserMapper.xml"/> </mappers> </configuration>
-
编写mybatis工具类**(MybatisUtils)**
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory 工厂 -> sqlSession
public class MybatisUtils {
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();
}
}
//SqlSession 包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.3 编写代码
-
实体类**【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; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
-
Dao接口**【Dao/Mapper】**
public interface UserDao { List<User> getUserList(); }
-
接口实现类【由原来的UserDaoImpl(接口实现类)转化为一个Mapper配置文件】
【namespace:接口】
【id:接口中的方法】
【resultType:返回类型】
<?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">
<mapper namespace="dao.UserDao">
<select id="getUserList" resultType="pojo.User">
select * from mybatis.user
</select>
</mapper>
-
在核心配置文件中将mapper.xml注册
<mappers> <mapper resource="dao/UserMapper.xml"/> </mappers>
2.4 测试
【常见出现的错误】
-
org.apache.ibatis.binding.BindingException: Type interface dao.UserDao is not known to the MapperRegistry.
【核心配置文件中需要注册mapper】
<mappers> <mapper resource="dao/UserMapper.xml"/> </mappers>
-
Junit测试
@Test public void test(){ //第一步:获取SqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //执行SQL UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } //关闭sqlSession sqlSession.close(); }
可能会遇到的问题
1.配置文件没有注册
2.绑定接口错误
3.方法名不对
4.返回类型不对
5.Maven导出资源问题
3、CRUD(增删改查)
3.1 增加接口方法
public interface UserMapper {
List<User> getUserList();
//查询用户
User getUserById(int id);
//新增用户
int addUser(User user);
//删除用户
int deleteUser(int id);
//更改用户
int updateUser(User user);
}
3.2 在mapper配置文件中用sql实现
<mapper namespace="dao.UserMapper">
<select id="getUserList" resultType="pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" resultType="pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="pojo.User">
insert into mybatis.user (id,name,pwd)
values (#{id},#{name},#{pwd});
</insert>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
<update id="updateUser" parameterType="pojo.User">
update mybatis.user
set name = #{name},pwd = #{pwd}
where id = #{id};
</update>
</mapper>
- namespace:要实现mapper接口的包名
- id :对应mapper接口中的方法名
- resultType:返回类型
- parameterType:参数类型
3.3 测试
@Test
public void testUpdateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(1,"haha","1233"));
sqlSession.commit();
sqlSession.close();
}
- 获取SqlSession对象
- 根据SqlSession对象获取mapper
- 调用mapper中的方法
- 增删改需要提交commit
- 关闭SqlSession
4、万能Map 【局部修改】
【当字段或者参数过多时,使用Map】
4.1 增加接口方法
int addUser2(Map<String ,Object> map);
4.2 在mapper配置文件中实现接口方法
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,pwd)
values (#{userId},#{userPwd});
</insert>
4.3 测试
@Test
public void testAddUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String ,Object> map = new HashMap<String ,Object>();
map.put("userId",3);
map.put("userPwd","123456");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
5、模糊查询
- 在Java代码执中使用,传统通配符:
- % 0个或多个字符
- _ 1和字符
- [charlist] 字符列中任意单一字符
- [!charlist] 或 [ ^charlist ] 不在字符列中的任意单一字符
List<User> getUserList2(String value);
<select id="getUserList2" resultType="pojo.User">
select * from mybatis.user where name like concat('%',#{value},'%')
</select>
@Test
public void testGetUserList2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList2 = mapper.getUserList2("李");
for (User user : userList2) {
System.out.println(user);
}
sqlSession.close();
}
6、配置解析
6.1 核心配置文件
-
mybatis-config.xml
-
有影响MyBatis行为的设置和属性信息
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
6.2 环境配置(environment)
Mybatis可以配置成适应多种环境
但每个SqlSessionFactory实例只能选择一种环境
Mybatis默认的事务管理器是JDBC,连接池:POOLED
6.3 属性(properties)
可以通过properties属性实现引用配置文件
编写一个配置文件db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
username=root
password=123456
在核心配置文件中引入
<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>
- 可以直接引入外部文件
- 可以在其中增加一些属性
- 如果两个文件有同一个字段,优先使用外部配置文件的!
6.4 类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字。
- 它仅用于 XML 配置,意在降低冗余的全限定类名书写
(1)可以给实体类起别名
<typeAliases>
<typeAlias type="pojo.User" alias="User"/>
</typeAliases>
(2)也可以指定一个包名,默认是这个类的类名,首字母小写
<typeAliases>
<package name="pojo"/>
</typeAliases>
在实体类比较少的时候用第一种
实体类多,建议使用第二种
第一种可以DIY别名,第二种要改的话需要在实体类增加注解@Alias
@Alias("hollow")
public class User {}
6.5 设置(settings)
6.5 映射器(mappers)
方式一:绑定配置文件
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件注册绑定
<mappers>
<mapper class="dao.UserMapper"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
6.6 生命周期和作用域
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
-
一旦创建了 SqlSessionFactory,就不再需要它了
-
局部变量
SqlSessionFactory:
-
数据库连接池
-
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
-
最简单的就是使用单例模式或者静态单例模式。
SqlSession:
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要关闭,否则资源被占用
每一个Mapper,代表一个具体的业务
7、解决属性名和字段名不一致的问题
7.1 问题
当数据库字段和实体类属性名字不一致时,取不到相应的数据
7.2 resultMap
结果集映射
id name pwd 数据库
id name passwor 实体类
<mapper namespace="dao.UserMapper">
<resultMap id="UserMap" type="User">
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserList" resultMap="UserMap">
select * from mybatis.user
</select>
</mapper>
-
id :resultMap的名字
-
type:实体类的名字
-
column:数据库的字段名
-
property:实体类的属性名
-
resultMap
元素是 MyBatis 中最重要最强大的元素 -
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
8、日志
8.1 日志工厂
如果一个数据库操作,出现了日常,需要排错,日志就是最好的助手
曾经:sout、debug
现在:日志工厂
- SLF4J
- LOG4J【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING【掌握】
- NO_LOGGING
STDOUT_LOGGING 标准日志输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
8.2 Log4j
什么是Log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
- 这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1.导入log4j包
<dependencies>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
2.log4j.propertie配置文件
#将等级为DEBUG的日志信息输出到console和fiLe这两个目的地,console和fiLe的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
1og4j.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
1og4j.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.sq1.ResultSet=DEBUG
log4j.logger.java.sq1.PreparedStatement=DEBUG
3.配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
简单实用
1.在使用Log4j的类中,导入包
import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserMapperTest.class);
3.日志级别
logger.info("info:进入了testLog4j");
logger.error("error:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
9、分页
为什么要分页?
- 减少数据的处理量
9.1使用Limit分页
语法:select * from user limit startIndex,pageSize;
select * from user limit 3; #【0,3】
- startIndex:开始下标
- pageSize:分页的大小
使用Mybatis实现分页
1、接口
List<User> getUserListByLimit(Map<String,Object> map);
2、Mapper.xml
<select id="getUserListByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
3、测试
@Test
public void testGetUserListByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String ,Object> map = new HashMap<String,Object>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserListByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
9.2 使用RowBounds分页【了解】
在java代码中实现分页
9.3 分页插件PageHelper
10、使用注解开发
1.注解在接口上实现
@Select("select * from user")
List<User> getUserList();
2.需要在核心配置文件中绑定接口
<mappers>
<mapper class="dao.UserMapper"/>
</mappers>
3.测试
本质:反射机制实现
底层:动态代理
自动提交事务
//SqlSession 包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
关于@Param()注解【给参数命名】
- 基本类型的参数或String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型,可以忽略,但是建议加上
@Select("select * from user where id = #{id}")
User getUserById(@Param("id")int id);
11、使用Lombok插件
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
-
java library
-
plugs
-
build tools
-
with one annotation your class
1.在IDEA中安装
2.在pom.xml配置文件中导入依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
3.在实体类上加注解
@Getter and @Setter
@FieldNameConstants
@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
【常用】:
@Data:
无参构造,get、set、tostring、hashcode、equals
@AllArgsConstructor
有参构造函数
@NoArgsConstructor
无参构造函数
@Data
@AllArgsConstructor
@NoArgsConstructor
12、多对一(对象用association)
按照查询嵌套处理(子查询)【麻烦】
按照结果嵌套处理
<mapper namespace="dao.StudentMapper">
<select id="getStudentList" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
</mapper>
实体类
Student
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private Teacher teacher;
}
Teacher
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
13、一对多(集合用collection)
实体类
Student
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
Teacher
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
List<Student> students;
}
按照结果嵌套处理
<mapper namespace="dao.TeacherMapper">
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<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>
14、多对一和一对多小结
1.关联 - association【多对一】
2.集合 - collection【一对多】
3.javaType & ofType
- javaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或集合,泛型中的pojo类型,泛型的约束型
15、动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
本质还是SQL,只是我们可以在SQL层面,去执行一个逻辑代码
环境搭建
实体类
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
获取随机ID
import java.util.UUID;
public class IDutils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
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>
choose (when, otherwise)【选择第一个满足条件的sql语句】
<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>
where【where 1=1 不安全】
- where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。
- 若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<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>
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>
trim
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
<trim prefix="SET" suffixOverrides=",">
...
</trim>
-
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容
-
suffixOverrides覆盖了后缀值设置,并且自定义了前缀值。
SQL片段
将一些功能的部分抽取出来,进行复用
1.使用SQL标签抽取公共部分
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
author = #{author}
</if>
</sql>
2.在需要的使用地方使用include
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<include refid="if-title-author"></include>
</set>
where id = #{id};
</update>
注意事项:
- 基于单标定义SQL片段
- 不要存在where标签
foreach
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
SQL
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
-
collection 集合
-
item 集合项
-
open 开头
-
close 结尾
-
separator 分隔符
-
inde 迭代的序号
Test
@Test
public void testQueryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
map.put("ids",ids);
mapper.queryBlogForeach(map);
sqlSession.close();
}
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
16、缓存
16.1 简介
再次查询相同数据的时候,直接走缓存,就不需要走数据库了
1.什么是缓存【Cache】?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存中,用户去查询数据就不用从磁盘上查询,从而提高查询效率,解决了高并发系统的性能问题
2.为什么使用缓存?
- 减少和数据库交互的次数,减少系统开销,提高系统效率
3.什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据
16.2 Mybatis缓存
- Mybatis包含一个非常强大的查询缓存特性,可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
- Mybatis系统中默认定义了两级缓存:一级缓存 和 二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也成为本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
- 为了提高扩展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
16.3 一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
1.开启日志
2.测试在一个session中查询两次相同记录
3.查看日志输出
缓存失效的情况:
1.增删改操作
2.查询不同的东西
3.查询不同的Mapper.xml
4.手动清理缓存
小结:默认开启,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段有效
16.4 二级缓存
- 全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到耳机缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤:
1.开启全局缓存
<setting name="cacheEnabled" value="true"/>
2.在使用耳机缓存的Mapper中开启
<cache/>
也可以自定义参数
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试
1.问题:需要将实体类序列化,否则报错
Caused by: java.io.NotSerializableException: pojo.User
//实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private int id;
private String name;
private String pwd;
}
16.5 缓存原理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YzWag5sO-1639369564726)(C:\Users\11626\AppData\Roaming\Typora\typora-user-images\image-20211122213153515.png)]
16.6 自定义缓存Ehcache
17、CASE
1.父工程的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--父工程-->
<groupId>org.example</groupId>
<artifactId>MybatisTest</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/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.12</version>
</dependency>
</dependencies>
<!-- 在build中配置resources ,放置资源导出失败的问题-->
<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>
</project>
2.子工程的pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
3.db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
username=root
password=123456
4.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>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="pojo"/>
</typeAliases>
<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>
<mappers>
</mappers>
</configuration>
5.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
1og4j.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
1og4j.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.sq1.ResultSet=DEBUG
log4j.logger.java.sq1.PreparedStatement=DEBUG
6.MybatisUtils
package utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory 工厂 -> sqlSession
public class MybatisUtils {
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();
}
}
//SqlSession 包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}