狂神说Mybatis
环境:
- JDK 1.8
- Mysql 5.5
- maven 3.6.3
- IDEA
- Mybatis 3.5.2
基础:
- JDBC
- Mysql
- Java基础
- Maven
- junit
1.简介
1.1 什么是Mybatis
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.2 如何获取Mybatis
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
- github GitHub - mybatis/mybatis-3: MyBatis SQL mapper framework for Java
- 中文文档 mybatis – MyBatis 3 | 简介
1.3 持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 数据库,io文件持久化
为什么要持久化
内存断电,文件就丢失了,但是有些文件不能丢失,所以要持久化
1.4 持久层
完成持久化工作的代码块
1.5 为什么需要Mybatis
-
帮助程序员将数据存储到数据库中
-
方便
-
传统的JDBC太繁琐了 (简化操作)
-
优点
- 简单易学
- 灵活
- 解除sql与程序代码的耦合,sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
-
使用的人很多
2.第一个Mybatis程序
2.1 环境搭建
- 搭建一个数据库
CREATE DATABASE mybatis
CREATE TABLE USER(
id INT NOT NULL PRIMARY KEY,
NAME VARCHAR(20) DEFAULT NULL,
pwd VARCHAR(20) DEFAULT NULL
)
INSERT INTO USER VALUES (1,'kuquan','123'),(2,'BAO','123'),(3,'root','123')
2.创建项目
3.编写mybatis的核心配置文件
<?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核心配置文件-->
<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="123"/>
</dataSource>
</environment>
</environments>
</configuration>
4.编写mybatis工具类
package utils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
/*
sqlsessionfactory
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
// 获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.2 编写代码
- 编写工具类
package bean;
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接口
import bean.User;
import java.util.List;
public interface UserDao {
List<User> getAllUser();
}
- 接口实现类由原来的类转变为一个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 namespace="dao.UserDao">
<select id="getAllUser" resultType="bean.User">
select * from mybatis.user
</select>
</mapper>
2.3 测试
注意点
org.apache.ibatis.binding.BindingException: Type interface dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
每一个mapper.xml都需要在Mybatis核心配置文件中注册
<mappers>
<mapper resource="dao/UserMapper.xml"></mapper>
</mappers>
maven运行时资源丢失问题
在pom.xml中加入如下配置(原因是maven的约定大于配置,不具体解释)
<!--在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>
结果:
3.CRUD
增删改查
3.1 Select标签
- id:对应的namespace里的方法名
- resultType:SQL语句的返回值
- parameterType:参数类型
<select id="getUserByID" resultType="bean.User" parameterType="int">
select * from mybatis.user where id=#{id}
</select>
3.2 Insert
<insert id="addUser" parameterType="bean.User">
insert into mybatis.user values (#{id}, #{name}, #{pwd})
</insert>
3.3 Update
<update id="updateUser" parameterType="bean.User">
update mybatis.user set name=#{name}, pwd=#{pwd} where id=#{id}
</update>
3.4 Delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
注意点
增删改需要提交事务
3.5 万能map
传递map的key对应的val值
假设,我们的实体类,或者数据库中的表的字段太多,我们应当使用map
// 抽象方法
int addUserOther(Map<String, Object> map);
// 配置文件
<insert id="addUserOther" parameterType="map">
insert into mybatis.user values (#{id}, #{name}, #{pwd})
</insert>
// 测试方法
@Test
public void addUserOther(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 5);
map.put("name", "demo");
map.put("pwd", "123");
int res = mapper.addUserOther(map);
System.out.println(res);
// 提交事务
sqlSession.commit();
sqlSession.close();
}
使用map,我们可以根据需要给参数,而不用拘泥具体的bean类
-
map传递参数,直接在sql中取出key即可!
-
对象传递参数,直接在sql中取对象的属性即可
-
只有一个基本参数的情况下,可以直接在sql中取到
-
多个参数用map或者注解
4.配置解析
4.1 核心配置文件
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
4.2 环境配置
MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
Mybatis默认的事务管理器是JDBC,连接池是POOLED
4.3 属性
我们可以通过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=123
- 在核心配置文件引入
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>
<!--引入外部配置文件(文件在资源文件夹下)-->
<properties resource="db.properties" />
- 可以在里面增加一些属性配置(优先使用外部配置文件的)
4.4 类型别名
类型别名可为 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>
每一个在包 domain.blog
中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author
的别名为 author
;若有注解,则别名为其注解值。
通过注解起别名
@Alias("hhh")
public class 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 的运行时行为。
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
4.6 其他
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- MyBatis plus
4.7 映射器
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
注意点
- 接口和其配置文件必须同名
- 接口和其配置文件必须在一个包下
4.8 生命周期和作用域
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
。
sqlSessionFactoryBuilder
- 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
sqlSessionFactory
- 可以理解为数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- SqlSessionFactory 的最佳作用域是应用作用域
- 最简单的方式就是使用单例模式或者静态单例模式
sqlSession
- 每个线程都应该有它自己的 SqlSession 实例,连接到连接池的一个请求
- 关闭
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
- 用完之后需要关闭,否则资源被占用
每一个Mapper都是一个具体的业务!
5.ResultMap(解决属性名和字段名不一致的问题)
5.1 问题引出
数据库中的字段:
public class User {
private int id;
private String name;
private String password; // 属性名和字段中的名称不一样
}
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
测试出现问题,修改bean里的user类之后,获取的数据出现问题
解决办法(1):
-
起别名
<select id="getUserByID" resultType="bean.User" parameterType="int"> select id,name,pwd as password from mybatis.user where id=#{id} </select>
5.2 resultMap(结果集映射)
id name pwd
变成
id name password
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<!--同时修改标签中的resultType为resultMap-->
<select id="getUserByID" resultMap="UserMap" parameterType="int">
select * from mybatis.user where id=#{id}
</select>
通过上述方式也可以解决数据库和java代码字段名不一致的问题
resultMap
元素是 MyBatis 中最重要最强大的元素。- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
- ResultMap 的优秀之处在于,只需要配置不同的即可
6.日志
6.1 日志工厂
如果一个数据库操作出现异常,我们需要排错.日志就是最好的助手!
曾经:sout,debug
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2EapB3R9-1631800943192)(Mybatis.assets/image-20210913143724549.png)]
- SLF4J
- LOG4J [掌握]
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING [掌握]
- NO_LOGGING
在mybatis中具体使用哪个日志实现,在设置中设定!
6.1.1STDOUT_LOGGING 标准日志输出
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/> <!--标准日志-->
</settings>
注意settings在xml中的位置
添加日志之后的效果
6.1.2 LOG4J
标准日志输出可以直接使用,但是LOG4J不能直接使用,需要额外导包
介绍
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,我们也可以控制每一条日志的输出格式,通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程,最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
LOG4J依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
LOG4Jproperties
#将等级为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/kuquan.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{yyyy-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的使用
运行之前的测试demo
简单使用
- 在要使用的log4j的类中,导入包import org.apache.log4j.Logger
- 日志对象,参数为当前类的class
// 获取日志对象
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 日志的三种级别
public void testLOG4J(){
logger.info("info:进入了testLOG4J()方法");
logger.debug("debug:进入了testLOG4J()方法");
logger.error("error:进入了testLOG4J()方法");
}
7.分页
为什么要分页?
- 减少数据的处理量
7.1 使用limit分页
select * from user limit start,pageSize
使用mybatis实现分页,核心SQL
- 接口
List<User> getUserLimit(Map<String, Integer> map);
- Mapper.xml
<select id="getUserLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
- 测试
@Test
public void getUserLimit(){
logger.info("into getUserLimit()");
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex", 0);
map.put("pageSize", 2);
List<User> users = mapper.getUserLimit(map);
for(User u : users)
System.out.println(u);
sqlSession.close();
}
7.2 使用RowBounds分页
不再使用sql实现分页,而是使用面向对象的方式,但是其底层还是limit
- 接口
List<User> getUserRowBounds();
- mapper.xml
<select id="getUserRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
- 测试
@Test
public void getUserRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
// RowBounds
RowBounds rowBounds = new RowBounds(0, 3);
// 通过java代码实现分页
List<User> list = sqlSession.selectList("dao.UserDao.getUserRowBounds", null, rowBounds);
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
- 结果
7.3 分页插件
了解即可
8.注解开发
8.1 什么是面向接口编程?
真正的开发中,我们会选择面向接口编程.
根本原因:解耦,可拓展,提高复用,开发分层,上层不用管具体的实现,大家遵守共同的标准,使得开发变得容易,规范性更好.
8.2 使用注解开发
一般只用来处理简单的语句,复杂的语句还是依赖xml来实现
- 注解在接口上实现
@Select("select * from mybatis.user where id=#{id}")
User getUserByID(int id);
- 需要在核心配置文件上绑定接口
<mappers>
<mapper class="dao.UserDao"></mapper>
</mappers>
- 测试
@Test
public void test01(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 底层主要是反射
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserByID(1);
System.out.println(user);
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
8.3 CRUD
我们可以在工具类创建的时候实现自动提交业务!
// 设置自动提交事务的mybatis工具类
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.InputStream;
/*
sqlsessionfactory
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
// 传入true参数表示自动提交事务
return sqlSessionFactory.openSession(true);
}
}
一种书写规范
// 规范的写法,当有多个参数的时候(并且这些参数为基本类型时)添加上@Param注解
@Select("select * from mybatis.user where id=#{id} and name=#{name}")
User getUserByIDandName(@Param("id") int id, @Param("name") String name);
此时sql语句中的赋值以Param中的名称为准
不设置自动提交,那么进行增删改操作之后需要提交才能真正改变数据库.
例如:
@Test
public void test05(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int res = mapper.delUser(5);
System.out.println(res);
// 如果mybaits中不设置自动提交,那么需要提交事务才能真正修改数据库
if(res == 1) sqlSession.commit();
sqlSession.close();
}
当res返回值为1的时候,提交事务
例子:
@Select("select * from mybatis.user where id=#{id}")
User getUserByID(@Param("id") int id);
@Select("select * from mybatis.user where id=#{id} and name=#{name}")
User getUserByIDandName(@Param("id") int id, @Param("name") String name);
@Insert("insert into mybatis.user values(#{id},#{name},#{password})")
int addUser(User user);
@Update("update mybatis.user set name='demo1' where id=#{id}")
int updateUser(@Param("id") int id);
@Delete("delete from mybatis.user where id=#{id}")
int delUser(@Param("id") int id);
在mybatis的核心配置文件中设置接口的映射
<mappers>
<mapper class="dao.UserDao"></mapper>
</mappers>
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型,可以忽略,但是建议加上
- 我们在SQL中引用的就是我们在param里设定的属性名
关于#{}和${}
- #{}是预编译处理,$ {}是字符串替换。
- MyBatis在处理#{}时,会将SQL中的#{}替换为?号,使用PreparedStatement的set方法来赋值;MyBatis在处理 $ { } 时,就是把 ${ } 替换成变量的值。
- 使用 #{} 可以有效的防止SQL注入,提高系统安全性。
9.Lombok
9.1 简介
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.
ProjectLombok是一个java库,可以自动插入编辑器和构建工具,提高java的性能。
永远不要再编写另一个getter或equals方法,使用一个注释,您的类就有了一个功能齐全的生成器,自动化了日志变量,等等。
9.2 使用步骤
- 在idea中安装lombok
- 在项目中导入lombok的jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
- 在实体类或者字段上加
- lombok的所有注解
@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
experimental @var
@UtilityClass
Lombok config system
Code inspections
Refactoring actions (lombok and delombok)
常用
- @Data:生成无参构造,get,set,toString,hashCode,equals
- @AllArgsConstructor:有参构造函数
- @NoArgsConstructor:无参构造函数
10.复杂查询环境
10.1 多对一处理
- 多个学生对应一个老师
- 对于学生而言,关联:多个学生关联一个老师 [多对一]
- 对于老师而言,集合:一个老师有很多学生 [一对多]
建表and插入数据
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT 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);
测试环境搭建
- 导入lombok
- 新建实体类
- 新建Mapper接口
- 新建Mapper.xml文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件
- 测试
10.2 按照查询嵌套处理
对sql语句进行调整,然后按照嵌套查询的方式进行查询
<!--
思路:
1.查询所有的学生
2.根据查询出来的学生的tid查询对应的老师 子查询
-->
<resultMap id="StudentAndTeacher" type="Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--
复杂的属性需要单独处理
对象:association 多对一
集合:collection 一对多
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
<!--<collection property=""></collection>-->
</resultMap>
<select id="getStudent" resultMap="StudentAndTeacher">
select * from student
</select>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
10.3 按照结果嵌套处理
不修改sql语句,直接对查询结果进行处理
<!--========按照结果嵌套处理===========-->
<select id="getStudentAnother" resultMap="StudentAndTeacherAnother">
select student.id sid,student.name sname,teacher.name tname from student,teacher where student.tid=teacher.id
</select>
<resultMap id="StudentAndTeacherAnother" type="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
10.4 一对多处理
- 例如一个老师拥有多个学生,对于老师而言,就是一对多关系
修改实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias("Student")
public class Student {
private int id;
private String name;
private int tid; // 学生需要关联一个老师
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias("Teacher")
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
impl
// 获取指定老师的信息以及他所有的学生的信息
Teacher getTeacherByID(@Param("id") int id);
Mapper
<!--按结果嵌套查询-->
<select id="getTeacherByID" parameterType="int" resultMap="TeacherAndStudent">
select s.id sid,s.name sname,t.id tid,t.name tname from teacher t,student s where t.id=#{id} and t.id=s.tid
</select>
<resultMap id="TeacherAndStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<!--
javaType:指定属性类型
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
test
@Test
public void test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacherByID(1);
System.out.println(teacher);
sqlSession.close();
}
另一种Mapper写法
<select id="getTeacher" parameterType="int" resultMap="TeacherAndStudent2">
select * from teacher where id=#{id}
</select>
<select id="getStudent" parameterType="int" resultType="Student">
select * from student where tid=#{id}
</select>
<resultMap id="TeacherAndStudent2" type="Teacher">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudent"></collection>
</resultMap>
10.5 小结
- 关联-association [多对一]
- 集合-collection [一对多]
- javaType & ofType
-
- JavaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点
- 保持sql的可读性,尽量保证通俗易懂
- 注意一对多和多对一中,属性名和字段的问题
- 如果问题不好排查,可以使用日志,建议使用log4j
慢sql
面试高频
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化
11.动态sql
什么是动态sql?
动态sql就是指根据不同的条件生成不同的SQL语句
主要的标签
- 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 '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建基础工程
- 导包
- 编写配置文件
- 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias("Blog")
public class Blog {
private int id;
private String title;
private String author;
private Date creativeTime;
private int views;
}
- 编写实体类对应的Mapper接口和Mapper.xml文件
creativeTime和数据库中字段名create_time不一致
在一定程度上解决名称不一致问题,但是仅限于描述的类型
<!--将经典数据库命名转化为驼峰命名-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
- 添加数据
@Test
public void test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getID());
blog.setAuthor("狂神说");
blog.setTitle("mybatis");
blog.setCreateTime(new Date());
blog.setViews(999);
mapper.addBlog(blog);
blog.setId(IDutils.getID());
blog.setTitle("Java");
mapper.addBlog(blog);
blog.setId(IDutils.getID());
blog.setTitle("spring");
mapper.addBlog(blog);
blog.setId(IDutils.getID());
blog.setTitle("微服务");
mapper.addBlog(blog);
sqlSession.commit();
sqlSession.close();
}
11.1 if
- 测试方法
List<Blog> queryBlogIF(Map map); // 采用Map可以容易控制传入的参数
- mapper.xml
<select id="queryBlogIF" 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>
- demo
@Test
public void test03(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
// 可选项
//map.put("title", "Java");
//map.put("author", "狂神说");
List<Blog> blogList = mapper.queryBlogIF(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
11.2 choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
<otherwise>
views = #{views}
</otherwise>
</choose>
</where>
</select>
选择一个条件进行匹配,如果when里面没有,那么取otherwise里面的
11.3 trim (where, set)
- where
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
使用where对之前IF条件里的xml配置进行修改
<select id="queryBlogIF" 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>
同样实现了效果
- set
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="views != null">
views = #{views},
</if>
<if test="author != null">
author = #{author},
</if>
</set>
where id = #{id}
</update>
如果给定的where和set无法满足条件,那么就可以通过trim自定义想要的结果
所谓的动态sql,本质还是sql语句,只是我们可以在sql层面去执行一些逻辑代码
11.4 sql片段
有的时候我们可能会将一些公告的部分抽取出来方便复用
- 使用sql标签抽取公共部分
- 在需要使用的地方使用include引用
<!--sql片段-->
<sql id="titleAndAuthor">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
/*引用sql片段*/
<include refid="titleAndAuthor"></include>
</where>
</select>
注意
- 最好基于单表定义sql片段 (不要定义复杂的东西)
- 不要存在where标签
11.5 foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
<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>
- 样例
<!--获取id为1,2,4的blog-->
<select id="getByIDS" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
通过foreach可以动态拼接字符串
动态sql就是在拼接sql语句,我们只要保证sql的正确性,按照sql的格式去排列组合,就可以了
建议
- 现在mysql中写出完整的sql,然后再修改成动态sql实现通用即可
12.缓存(了解)
12.1 简介
查询: 链接数据库 耗费资源!
一次查询的结果,给他暂存再一个地方,下次用到直接取到 -----> 内存
我们再次查相同的数据就直接走内存而不是走数据库
什么是缓存[Cache]?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,这样用户查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高了效率,解决了高并发系统的性能问题.
为什么使用缓存?
- 减少和数据库交换的次数,减少系统开销,提高系统效率
什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据
12.2 Mybatis缓存
- mybatis具有一个强大的查询缓存特性,它可以非常方便地定制和配置缓存.缓存可以极大的提升查询效率.
- mybatis系统默认定义了两种缓存一级缓存和二级缓存
- 默认情况下,只有一级缓存开启.(sqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
- 为了提高拓展性,mybatis定义了缓存接口Cache.我们可以通过实现Cache接口来定义二级缓存
-
映射语句文件中的所有 select 语句的结果将会被缓存。
-
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
-
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
-
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
-
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
-
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
-
LRU
– 最近最少使用:移除最长时间不被使用的对象。 -
FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。 -
SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。 -
WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
12.3 一级缓存
- 一级缓存也叫本地缓存:
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试
- 开启日志
- 测试在一个session中查询两次记录(两次结果相同)
- 查看日志数据,看看sql执行了几次
- 结果
缓存失效的情况
- 查询的东西不同
- 增删改操作,可能会改变原来的数据,所以会清除缓存
- 查询不同的mapper.xml
- 手动清理缓存
sqlSession.clearCache();
一级缓存是默认开启的,无法关闭,只在一次sqlSession中有效,也就是获取连接到连接关闭的这个区间
12.4 二级缓存
- 二级缓存也叫全局缓存,一级缓存的作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被存放在当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了.一级缓存的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
步骤
- 开启全局缓存
<!--开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
- 在mapper.xml中添加cache标签
- 自定义参数
<!--在当前xml中使用二级缓存-->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" ></cache>
初始状态
<cache></cache>
-
测试
- 我们需要将实体类序列化!否则就会报错
@Data @AllArgsConstructor @NoArgsConstructor @Alias("User") public class User implements Serializable { private int id; private String name; private String pwd; }
小结
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会想放在一级缓存中
- 只有当前会话结束之后才会把一级缓存提交到二级缓存
12.5 缓存原理
缓存顺序
- 第一次查询先看二级缓存有没有,再看一级缓存有没有,都没有再查询数据库,然后结果放在一级缓存中
12.6自定义缓存 - ehcache
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
简介
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
现在更多的是使用redis,而不是使用ehcache
依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
再mapper中应用ehcache
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
配置ehcache.xml文件(在resource文件夹下)
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
总体来说,变化不大,并没有什么根本性的改变
=“true” >
初始状态
```xml
<cache></cache>
-
测试
- 我们需要将实体类序列化!否则就会报错
@Data @AllArgsConstructor @NoArgsConstructor @Alias("User") public class User implements Serializable { private int id; private String name; private String pwd; }
小结
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会想放在一级缓存中
- 只有当前会话结束之后才会把一级缓存提交到二级缓存
12.5 缓存原理
缓存顺序
- 第一次查询先看二级缓存有没有,再看一级缓存有没有,都没有再查询数据库,然后结果放在一级缓存中
12.6自定义缓存 - ehcache
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
简介
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
现在更多的是使用redis,而不是使用ehcache
依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
再mapper中应用ehcache
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
配置ehcache.xml文件(在resource文件夹下)
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
总体来说,变化不大,并没有什么根本性的改变
现在更多的使用Redis来做缓存,k-v