1.初识Mybatis
1.1怎么获取Mybatis
Maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
Github:Releases · mybatis/mybatis-3 · GitHub
Github:GitHub - tuguangquan/mybatis: mybatis源码中文注释
1.2持久层
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转换的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化。
- 类比生活中:冷藏、罐头等实现持久化
为什么需要持久化?
- 有一些对象,不能让他丢掉
- 内存太贵
1.3、持久层
Dao层、service层、Controller层
- 完成持久化工作的代码块
- 层界限十分明显
1.4为什么需要Mybatis?
- 帮助程序员将数据存入到数据库中。
- 方便
- 传统的JDBC代码太复杂。简化,框架。自动化
- 不用Mybatis也可以。更容易上手。技术没有高低之分
- 优点
- 简单易学
- 灵活
- sql和代码分离,提高了可维护性
- 提供映射标签,支持对象与数据库orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
最重要的一点:使用的人多
Spring SpringMVC SpringBoot
2.第一个Mybatis程序
思路:搭建环境--->导入Mybatis--->编写代码--->测试
2.1搭建环境
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user`(
id INT(20) PRIMARY KEY NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
pwd VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(id,`name`,pwd) VALUES
(1,'狂神','123456'),
(2,'张三','123456'),
(3,'李四','123456');
1.新建一个普通的Maven项目
2.删除Src
<?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>com.guigu</groupId>
<artifactId>Mybatis-Study</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--导入mybatis依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!--导入mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--导入junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
编写mybatis工具类
package com.atguigu.utis;
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;
/**
* @author tom
* @create 2022-06-29 17:06
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//配置文件名称
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
//获取流
inputStream = Resources.getResourceAsStream(resource);
//通过sql会话建造工厂去建造一个sql会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
}
}
public static SqlSession getSqlSeesion(){
//可以理解为getConnection()
return sqlSessionFactory.openSession();
}
}
2.3编写代码
- 实体类
package com.atguigu.pojo;
/**
* @author tom
* @create 2022-06-30 9:33
*/
public class User {
private int id;
private String name;
private String pwd;
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", 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;
}
}
- Dao接口
package com.atguigu.Dao;
import com.atguigu.pojo.User;
import java.util.List;
public interface UserDao {
public List<User> getUserList();
}
- 接口实现类由原来的UserDaoImpl转变为一个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">
<!--(帮对一个对应的Dao/Mapper接口)对应JDBC的实现接口-->
<mapper namespace="com.atguigu.Dao.UserDao">
<select id="getUserList" resultType="com.atguigu.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.4测试
注意点:1.Type interface com.atguigu.Dao.UserDao is not known to the MapperRegistry.
在mybatis-config中绑定配置文件。
<mappers>
<mapper resource="com.atguigu.Dao/UserMapper.xml"/>
</mappers>
2.java.lang.ExceptionInInitializerError
在pom.xml文件中添加:
<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>
MapperRegistry是什么?
核心配置文件中注册mappers
junit测试
package com.atguigu.Dao;
import com.atguigu.pojo.User;
import com.atguigu.utis.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//获取sqlSeesion对象
SqlSession sqlSeesion = MybatisUtils.getSqlSeesion();
//方式一:getMapper
UserDao mapper = sqlSeesion.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
userList.forEach(System.out::println);
//关闭sqlSeesion
sqlSeesion.close();
}
}
可能遇到的问题:
1.配置文件没有注册
2.绑定接口错误
3.方法名不对
4.返回类型不对
5.Maven导出资源问题
3.CRUD
1.namespace
namespace中的包名要和Dao/mapper接口的包名一致!
2.select
选择,查询语句
- id:对应的namespace中的方法名;
- resultType:sql语句执行的返回值!
- parameterType:参数类型!
编写接口
编写mapper中的sql语句
测试
<select id="getUserList" resultType="com.atguigu.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" resultType="com.atguigu.pojo.User" parameterType="int">
select * from mybatis.user where id=#{id}
</select>
3.insert
<insert id="addUser" parameterType="com.atguigu.pojo.User">
insert into mybatis.user (id,name,pwd) VALUES (#{id},#{name},#{pwd})
</insert>
4.update
<update id="updateUser" parameterType="com.atguigu.pojo.User">
update mybatis.USER SET name=#{name},pwd=#{pwd} WHERE id=#{id}
</update>
5.delete
<delete id="deleteUser" parameterType="int">
DELETE from USER where id=#{id}
</delete>
注意点:
- 增删改需要提交事务
读错从最后往前读
7.万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
//insert一个用户2
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,pwd) VALUES (#{id},#{pwd})
</insert>
Map传递参数,直接在sql中取出key即可!【parameterType="map"】
对象传递参数,直接在sql中取对象的属性即可!【parmeterType="Object"】
只有一个基本参数类型的情况下,可以直接在sql中取到!
多个参数用Map,或者注解!
8.模糊查询怎么写?
1.Java代码执行的时候传递通配符%%
List<User> likeUser = mapper.getLikeUser("%李%");
2.在sql拼接中使用通配符!
select * from user where name like "%"#{value}"%"
4.配置解析
1.核心配置文件
Mybatis-config.xml
Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2.环境配置(environments)
Mybatis可以配置成多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
3.属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置且可动态替换。既可以在典型的 Java 属性文件中配置,亦可以在 properties 元素的子元素来传递。
在核心配置中引入
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部文件
4.类型别名(typeAliases)
- 类型别名是为java类型设置一个短的名字。
- 存在的意义在于用来减少类完全限定名的冗余。
<!--可以给实体类配置别名-->
<typeAliases>
<typeAlias type="com.atguigu.pojo.User" alias="user"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!
<typeAliases>
<package name="com.atguigu.pojo"/>
</typeAliases>
在实体类比较少的时候使用方式一,实体类多时使用方式二
第二种方式可以使用注解更改别名:@Alias("com")
5.设置(Settings)
缓存与懒加载、日志实现
6.其他配置
plugins插件
mybatis-generator-core
mybatis-plus
通用mapper
7.映射器(mappers)
方式一:使用全路径
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="com/atguigu/Dao/UserMapper.xml"/>
</mappers>
方式二:废弃
方式三:使用类名(注意:1.接口需与配置文件同名2.两者必须在同一个包下)
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="com.atguigu.Dao.UserMapper"/>
</mappers>
方式四:使用扫描包注入绑定(注意:1.接口需与配置文件同名2.两者必须在同一个包下)
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
8.作用域(scope)和生命周期
生命周期和作用域是至关重要的,因为错误使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory:
可以看做数据库连接池
一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
因此最佳作用域是应用作用域
SqlSeesion:
可以看做Connection
线程不安全的,最佳作用域是请求或方法作用域,使用完后就关闭它,关闭曹祖是很重要的,应该把这个关闭操作放到finally块中以确保每次都没关闭
5.解决属性名和字段名不一致的问题
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
6.日志
6.1日志工厂
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的注释偶!
曾经:sout、debug
- SLF4J
- LOG4J(3.5.9 起废弃)
- LOG4J2【掌握】
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING【掌握】
- NO_LOGGING
在Mybatis中具体使用哪一个日志实现,在mybatis-config.xml中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2LOG4J
什么是LOG4J?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.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/lin.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
3.配置log4j为日志的实现
<!--日志设置 标准的日志工厂实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
4.LOG4J的使用!直接测试运行刚才的查询
简单使用
1.导入包:import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
7.分页
思考:为什么要分页?
减少数据库io开销
使用limit分页
select * from user limit 0,2
使用Mybatis实现分页:
@Test
public void getUserByLimtTest(){
SqlSession sqlSeesion = MybatisUtils.getSqlSeesion();
UserMapper mapper = sqlSeesion.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",3);
List<User> users = mapper.getUserByLimit(map);
for (User user : users) {
System.out.println(user);
}
}
7.2、RowBounds分页
不再使用SQL实现分页
1.接口
//分页2
List<User> getUsersByRowBounds();
2.mapper.xml
<select id="getUsersByRowBounds" resultType="com">
select * from user
</select>
3.测试(注意路径名大小写)
@Test
public void getUsersByRowBounds(){
SqlSession sqlSeesion = MybatisUtils.getSqlSeesion();
RowBounds rb = new RowBounds(1, 2);
List<User> userList = sqlSeesion.selectList("com.atguigu.Dao.UserMapper.getUsersByRowBounds", null, rb);
for (int i = 0; i <userList.size() ; i++) {
System.out.println(userList.get(i));
}
}
7.3分页插件
了解即可
8.面向接口编程
Java我们说它是面向对象的编程语言,但在真正的开发中,很多时候我们会选择面向接口编程
根本原因:解耦,把对象的约束与实现分开,提高扩展性、可复用性,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
8.2使用注解开发
1.注解在接口上实现
@Select("select * from user")
List<User> getUsers();
2.需要在核心配置文件中绑定接口
<mappers>
<mapper class="com.atguigu.Dao.UserMapper"/>
</mappers>
3.测试
本质:反射机制实现
底层:使用动态代理
Mybatis详细的执行流程
8.3CRUD
工具类可以实现自动提交事务
public static SqlSession getSqlSeesion() {
//可以理解为getConnection()
return sqlSessionFactory.openSession(true);//自动提交
}
接口
package com.atguigu.Dao;
import com.atguigu.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
/**
* @author tom
* @create 2022-06-30 9:37
*/
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
//当方法存在多个参数,所有参数前面加上@Param("")注解
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
void addUser(User user);
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
void updateUser(User user);
@Delete("delete from user where id=#{id}")
void deleteUserById(@Param("id") int id);
}
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
- 我们在SQL中引用的就是@Param()中设定的属性名!
#{} ${}区别
#{}可以防止SQL注入 添加的参数自动添加了""
${}会有SQL注入的问题 添加的参数没有""
9.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.
1.java library
2.plugs
3.build tools
使用步骤:
1.在IDEA中安装Lombok插件!
2.在项目中导入Lombokjar包!
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<!--<scope>provided</scope>-->
</dependency>
3.在实体类上加上注解即可!
@Data
@AllArgsConstructor
@NoArgsConstructor
Features
@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
10.多对一处理
多个学生对应一个老师
对于学生而言 关联 多对一
对于老师而言 集合 一对多
SQL
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 PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
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');
测试环境搭建
1.导入lombok
2.新建实体类Teacher、Student
3.新建接口及.xml文件TeacherMapper、StudentMapper
4.再核心配置文件中绑定注册接口
5.测试是否成功
按照查询嵌套处理
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师! 子查询
-->
<mapper namespace="com.atguigu.Dao.StudentMapper">
<select id="getStudents" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher
</select>
</mapper>
按照结果嵌套处理
<select id="getStudents2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname from teacher t,student s where t.id=s.tid
</select>
<resultMap id="StudentTeacher2" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
<!--<result property="tname" column="teacher"/>-->
</resultMap>
回顾Mysql多对一查询方式:
- 子查询
- 联表查询
11.一对多处理
比如一个老师拥有多个学生!
对于老师来说就是一对多
实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
//学生需要一关联一个老师
// private Teacher teacher;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> student;
}
按照结果嵌套处理:
按照查询嵌套处理:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.Dao.TeacherMapper">
<select id="getTeacher" resultMap="Teacher2">
select t.name tname,s.id sid,s.name sname from student s,teacher t where s.tid=t.id
</select>
<resultMap id="Teacher2" type="Teacher" >
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂属性我们需要单独处理,对象:assocation 集合:collection
javaType=""指定属性的类型!
集合中的泛型信息,我们使用ofType获取
-->
<collection property="student" ofType="Student" >
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id=#{id};
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="student" javaType="list" ofType="Student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select * from student where tid=#{id};
</select>
</mapper>
报错:
Ambiguous collection type for property 'student'. You must specify 'javaType' or 'resultMap'
解决方法:将实体类中 private List<Student> stuents 改为 private List<Student> stuent 配置文件
<collection property="students 改为 <collection property="student很无语,我还是没想明白这样为什么可以了,如果有大哥知道,希望可以跟我说一下
小结:
1.关联-association
2.集合-collection
3.javaType & ofType
1.javaType用来指定实体类中属性的类型
2.ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!(集合中存放数据的类型)
注意点:
- 保证SQL的可读性,通俗易懂
- 注意一对多和多对一中,属性名和字段的问题!
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
避免慢查询
面试高频
- mysql引擎
- innoDB底层原理
- 索引
- 索引优化!
12.动态SQL
什么是动态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 '博客',
`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
创建一个基础工程
1.导包
2.编写配置文件
<setting name="mapUnderscoreToCamelCase" value="true"/><!--开启驼峰命名映射-->
<mapper namespace="com.atguigu.Dao.BlogMapper">
<insert id="addBlog" parameterType="Blog">
insert into blog(id,title,author,create_time,views)
VALUES(#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
3.编写实体类
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
4.编写实体类对应的Mapper接口和Mapper.XML文件
IF
<select id="queryBlogsIf" 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>
choose、when、otherwise
<select id="queryBlogsIf" parameterType="map" resultType="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>
trim、where、set
<select id="queryBlogsIf" 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>
<update id="updateByTitle" parameterType="map">
update blog
<set>
<if test="views!=null">
views=#{views},
</if>
<if test="author!=null">
author=#{author},
</if>
</set>
<where>
<if test="title!=null">
title=#{title}
</if>
</where>
</update>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一个逻辑代码
SQL片段
有的时候我们可以把一些通用的功能提取出来复用
1.使用SQL标签抽取公共的部分
<sql id="query-if-author">
<if test="views!=null">
views=#{views},
</if>
<if test="author!=null">
author=#{author},
</if>
</sql>
2.在需要的地方使用include标签引用即可
<update id="updateByTitle" parameterType="map">
update blog
<set>
<include refid="query-if-author"/>
</set>
<where>
<if test="title!=null">
title=#{title}
</if>
</where>
</update>
注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where标签
Foreach
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,取排列组合就可以了
建议:
- 现在Mysql中写出完整的SQL再对应的去修改我们的动态SQL实现通用即可!
13.缓存
13.1简介
查询:连接数据库,很消耗资源
一次查询的结果,给他暂存再一个可以直接取到的地方!--->内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
缓存用来解决多并发的性能问题
为什么使用缓存?
减少数据库交互次数,减少系统开销,提高系统效率
什么样的数据能使用缓存?
经常查询并且不经常改变的数据
测试步骤:
1.开启日志
2.在一个Sesion中相同的语句查询两次
3.查看日志输出
缓存失效的情况:
1.两条相同语句的中间有增删改语句,可能会改变数据,所以必定会刷新缓存!
2.查询不同的数据
3.查询不同的Mapper.xml
4.手动清理缓存!
一级缓存默认是开启的,只在一次SQLSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存就是一个Map
13.2二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个Mapper.xml对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这条数据就会存放在一级缓存中
- 如果当前会话关闭了,一级缓存中的数据将被保存到二级缓存中
- 新的会话查询信息,可以从二级缓存中获取结果
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤:
1.开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存对的Mapper中开启
<!--开启二级缓存-->
<!--
输入输出规则:先进先出
60s刷新一次
最大存储512个引用
只读
-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试
问题:当我们没有设置输入输出规则时,需要将实体类序列化!
implements Serializable
小结:
- 只要开启二级缓存,在同一个Mapper下就有效
- 所有数据都会先放在一级缓存中
- 只有当会话提交或关闭,才会存储到二级缓存中
13.3自定义缓存-ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
要在程序中使用ehcache,首先要导包
<!-- 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>
在Mapper中指定使用ehcache
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
ehcache.xml
<?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:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home-用户主目录
user.dir-用户当前工作目录
java.io.tmpdir-默认临时文件路径
-->
<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"/>
<!-- 如果缓存支持硬盘存储,则指定硬盘的存储路径 -->
<!--
maxElementsInMemory="10000": 内存中支持的最大对象存储数量
eternal="false": 是否在内存中永久存储. 建议为false,如果为true,则后面两个参数无效,即不会有时间的限制
timeToIdleSeconds="20": 如果20秒没有访问此对象,则对象销毁
timeToLiveSeconds="120" 对象的总存活时间,120之后无论访问多么频繁都会销毁
overflowToDisk="true": 是否支持溢出到硬盘, 建议为true
memoryStoreEvictionPolicy="LRU" 内存的替换算法
FIFO 先进先出
LRU 按时间计算
LFU 按频率计算
diskPersistent="false" 是否支持硬盘的持久化, 多个相同的项目共享数据
diskExpiryThreadIntervalSeconds="120" 存储到硬盘中的时间,100秒,则如果下此JVM启动的时间间隔少于100则可以访问到前面的数据,否则访问不到
-->
</ehcache>
Redis数据库来做缓存。K-V键值对