什么是MyBatis
-
MyBatis 是一款优秀的持久层框架
-
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程
-
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
-
MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。
-
2013年11月迁移到Github .
-
Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
-
GitHub : https://github.com/mybatis/mybatis-3
持久化
持久化是将程序数据在持久状态和瞬时状态间转换的机制。
-
即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中、XML数据文件中等等。
-
JDBC就是一种持久化机制。文件IO也是一种持久化机制。
-
在生活中 : 将鲜肉冷藏,吃的时候再解冻的方法也是。将水果做成罐头的方法也是。
为什么需要持久化服务呢?那是由于内存本身的缺陷引起的
-
内存断电后数据会丢失,但有一些对象是无论如何都不能丢失的,比如银行账号等,遗憾的是,人们还无法保证内存永不掉电。
-
内存过于昂贵,与硬盘、光盘等外存相比,内存的价格要高2~3个数量级,而且维持成本也高,至少需要一直供电吧。所以即使对象不需要永久保存,也会因为内存的容量限制不能一直呆在内存中,需要持久化来缓存到外存。
持久层
什么是持久层?
-
完成持久化工作的代码块 . ----> dao层 【DAO (Data Access Object) 数据访问对象】
-
大多数情况下特别是企业级应用,数据持久化往往也就意味着将内存中的数据保存到磁盘上加以固化,而持久化的实现过程则大多通过各种关系数据库来完成。
-
不过这里有一个字需要特别强调,也就是所谓的“层”。对于应用系统而言,数据持久功能大多是必不可少的组成部分。也就是说,我们的系统中,已经天然的具备了“持久层”概念?也许是,但也许实际情况并非如此。之所以要独立出一个“持久层”的概念,而不是“持久模块”,“持久单元”,也就意味着,我们的系统架构中,应该有一个相对独立的逻辑层面,专注于数据持久化逻辑的实现.
-
与系统其他部分相对而言,这个层面应该具有一个较为清晰和严格的逻辑边界。【说白了就是用来操作数据库存在的!】
为什么需要Mybatis
-
Mybatis就是帮助程序猿将数据存入数据库中 , 和从数据库中取数据 .
-
传统的jdbc操作 , 有很多重复代码块 .比如 : 数据取出时的封装 , 数据库的建立连接等等... , 通过框架可以减少重复代码,提高开发效率 .
-
MyBatis 是一个半自动化的ORM框架 (Object Relationship Mapping) -->对象关系映射
-
所有的事情,不用Mybatis依旧可以做到,只是用了它,所有实现会更加简单!技术没有高低之分,只有使用这个技术的人有高低之别
-
MyBatis的优点
-
简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件就可以了,易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
-
灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
-
解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
-
提供xml标签,支持编写动态sql。
-
.......
-
-
最重要的一点,使用的人多!公司需要!
一.第一个mybatis程序
1.注意事项
1. mybatisconfig中需要绑定mapper 2. 8.0版本的数据库,连接语句需要修改 3. 需要在maven中添加过滤 4. 输出对象时候自动调用toString() 5。 命名空间的作用:绑定接口 6. 流程 先写工具类,添加配置文件(连接数据库,写实体类,写接口(原来写实现类,现在写mapper,测试的时候直接调用mapper中的方法
http响应就是网页请求,网页请求之后都会访问数据库,创建Sesssion ,需要记得关闭
mybatis.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>
<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://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/cr/dao/UserMapper.xml"/>
</mappers>
</configuration>
静态资源过滤
<?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.cr</groupId>
<artifactId>Mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>mybatis</module>
</modules>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
工具类
package com.cr.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;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//sqlSession包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
UserMapper.xml
namespace写绑定的接口名字,select id处写类名
<?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="com.kk.dao.UserMapper">
<select id="getUserList" resultType="com.kk.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.kk.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.kk.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.kk.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
</mapper>
UserDao
package com.kk.dao;
import com.kk.pojo.User;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public interface UserMapper {
List<User> getUserList();
//根据id查询用户
User getUserById(int id);
//插入用户
int addUser(User user);
//更新用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
}
测试类
package com.cr.dao;
import com.cr.pojo.User;
import com.cr.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
/*问题:
1. mybatisconfig中需要绑定mapper
2. 8.0版本的数据库,连接语句需要修改
3. 需要在maven中添加过滤
4. 输出对象时候自动调用toString()
5。 命名空间的作用:绑定接口
6. 流程 先写工具类,添加配置文件(连接数据库,写实体类,写接口(原来写实现类,现在写mapper,测试的时候直接调用mapper中的方法
* */
@Test
public void test(){
//从sqlSession中需要执行sql,执行sql要么从.xml要么从mapper,mapper和dao是一个东西
//mapper是dao的实现类,面向接口变成拿到接口就可以,返回接口就可以执行里面的方法
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
//方式1
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
实体类
package com.cr.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 + '\'' +
'}';
}
}
步骤:
- 先写工具类(被迫需要一个配置文件)
- 写Mybatis配置文件
- 写实体类
- 写接口
- 写Mapper.xml
- 写Test
- 加静态过滤(pom.xml)
二.增删改查
1.数据库事务
1)在A窗口中先开启事务,然后执行张三账户-500,-》出错了-》李四账户+500,此时查询A窗口数据,张三确实-500,但李四还是100;在B窗口中查询数据,张三和李四都是1000,没发生变化;说明A窗口中开启事务起了作用,且A中查询的数据也只是暂时的。
2)发现错误后,执行回滚操作,再次在窗口A和B中查询,数据都是1000,回滚操作成功。
3)在A窗口中先开启事务,然后执行张三账户-500-》李四账户+500,此时查询A窗口数据,张三确实-500,李四+500;在B窗口中查询数据,张三和李四都是1000,没发生变化;因在A窗口中的操作都OK,执行提交事务,再次在窗口A和B中查询,数据都发生正确变化,事务提交成功。
2.编译过程
- Mybatis、工具类、实体类不需要修改
- 先写接口UserMapper
- 写实现类,userMapper.xml
- 写测试类(增删改需要提交事务)
<?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="com.cr.dao.UserMapper">
<select id="getUserList" resultType="com.cr.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.cr.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.cr.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.cr.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
</mapper>
3.万能的Map
<update id="updateUser" parameterType="com.cr.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String,Object>();
map.put("userid",5);
map.put("userName",5);
map.put("userpwd",5);
userDao.addUser2();
sqlSession.commit();
sqlSession.close();
}
3.环境配置
- 学会配置多套运行环境(选择id mybatis配置文件:default处)
- 默认事务管理器 JDBC
- 连接池:POOLED
三.配置优化
1.属性优化(properties)
1.编写db.properties
driver:com.mysql.cj.jdbc.Driver
url:jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8
username:root
password:123456
2.别名优化(typeAliases)
- 类型别名为了给java类型设置一个短的名字,如com.kk.pojo.User在resultType中可直接写为user
- 存在的意义:减少类完全限定名的冗余
方式一:
方式二:扫描实体类的包,默认别名就是这个类的类名,首字母小写。
可以用注解在diy别名
在实体类少的时候,使用第一种方式,实体类十分多,使用第二种!
第一种可以diy,第二种则不行,如果非要改,可以用注解!
3.设置(settings)
日志实现:
缓存和懒加载:
4.其他配置(不需要过多了解)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
5.映射器(mappers)
MapperRegistrt:注册绑定我们的Mapper文件
方式一:【推荐使用】
方式二:使用class文件绑定注册
注意点:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一个包下
方式三:使用扫描包进行绑定
注意点:
- 接口和他的Mapper配置文件必须同名
- 接口和他的Mapper配置文件必须在同一个包下
6.操作要点
- 将数据库配置文件外部引入
- 实体类别名
- 保证UserMapper接口和UserMapper.xml改为一致,并且放在同一个包下!
7.生命周期和作用域
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
- 一旦创建了SqlSessionFactory 就不再需要他了
- 局部变量
SqlSessionFactory:
- 说白了可以想象为:数据库连接池
- 最佳作用域:应用作用域(一个application)
- 一旦被创建就应该在应用的运行期间一直存在,没有理由丢弃或者重新创建另一个实例
- 最简单的就是使用单例模式或者静态单例模式
SqlSession:
- 连接到连接池的一个请求!
- 最后需要关闭
- 最佳作用域:方法作用域,用完后需要关闭,否则资源被占用。
这里的每一个Mapper都对应一个具体的业务!
四.解决属性名和字段名不一致的问题
1.问题
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
测试出现问题
解决方法:
- 起别名
<select id="getUserById" parameterType="int" resultType="com.kk.pojo.User"> select id,name,pwd as password from mybatis.user where id = #{id} </select>
2.resultMap
结果集映射
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段 property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
- resultMap元素是MyBatis中最终于最强大的元素‘
- ResultMap的设计思想是,对于简单语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需描述它们的关系就行了
- ResultMap最优秀的地方在于,虽然你对他已经相当了解了,但是根本不需要显式的用到他们
五.日志
1.日志工厂
如果一个数据库操作出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout debug
现在:日志工厂!
- SLF4J
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING (一个工具包)
- STDOUT_LOGGING (控制台输出) 【掌握】
- NO_LOGGING
在Mybatis中具体使用哪个日志实现,在设置中设定!
在Mybatis核心配置文件中,配置我们的日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2.Log4j
什么是LOG4J?
1.先导入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/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
3.配置log4j为日志输出方式
<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");
- 设置后每次编译会生成log文件,在文件中前面标记有info、debug、error等
六.分页
思考:为什么要分页?
减少数据的处理量
使用limit分页
SELECT * from user limit 3; //相当于从[0,3]
SELECT * from user limit 2,2 ; 相当于一页[2,2]
1.使用Mybatis实现分页,核心SQL
1.接口
List<User> userByLimit = mapper.getUserByLimit(map);
2.Mapper.xml
<select id="getUserByLimit" parameterType="map" resultType="user" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
3.测试代码
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userByLimit = mapper.getUserByLimit(map);
for (User user : userByLimit) {
System.out.println(user);
}
sqlSession.close();
}
2.RowBounds分页
不再使用SQL实现分页
1.接口
List<User> getUserByRowBounds();
2..xml
<select id="getUserByRowBounds" resultMap="UserMap">
select *
from mybatis.user;
</select>
3.测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(1,2);
List<User> userList = sqlSession.selectList("com.kk.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
3.分页插件
了解即可,万一架构师说要使用,需要知道是什么东西!
七.使用注解开发
1.面向接口编程
面向接口编程
-
大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
-
根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
-
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
-
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
-
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
-
接口的本身反映了系统设计人员对系统的抽象理解。
-
接口应有两类:
-
第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
-
第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
-
-
一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
-
面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法 .
-
面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现 .
-
接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构
2.使用注解开发
反射:可以获取方法的所有东西,包括参数名字、返回值、注解。
注解开发:利用反射实现
1.注解在接口上实现
@Select("select * from mybatis.user")
List<User> getUser();
2.配置文件中绑定接口
<mappers>
<mapper class="com.kk.dao.UserMapper"/>
</mappers>
3.测试
本质:反射机制实现
底层:动态代理
面试高频:代理模式,单例模式,工厂模式等
Mybatis的详细执行流程
3.CRUD
设置为true后自动提交事务
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); }
接口
package com.kk.dao;
import com.kk.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> getUser();
// 方法存在多个参数,所有的参数前必须加@Param
@Select("select * from mybatis.user where id=#{id}")
User getUserByID(@Param("id") int id2);
//此处的values后面的id/name/password要与实体类保持一致
@Insert("insert into mybatis.user(id, name, pwd) values (#{id},#{name},#{password})")
int addUser(User user);
@Update("update mybatis.user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from mybatis.user where id=#{did}")
int deleteUser(@Param("did") int id);
}
测试类
import com.kk.dao.UserMapper;
import com.kk.pojo.User;
import com.kk.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.getUser();
for (User user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}
@Test
public void getUserByID() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
sqlSession.close();
}
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.addUser(new User(6, "gxf", "sdiiewew"));
if (i > 0) {
System.out.println("插入成功");
}
sqlSession.close();
}
@Test
public void updateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.updateUser(new User(5, "fkkk", "sdi222w"));
if (i > 0) {
System.out.println("修改成功");
}
sqlSession.close();
}
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(7);
if (i > 0) {
System.out.println("删除成功");
}
sqlSession.close();
}
}
[必须要将接口主动注册绑定到我们的核心配置文件中]
<mappers>
<mapper class="com.kk.dao.UserMapper"/>
</mappers>
</configuration>
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话可以忽略。
- 在SQL语句id=#{uid}中引用的就是@param(“uid”)这里设置的
#{}¥{}
#{}能防止sql注入
八.Lombok
1.使用步骤:
1.在IDEA中安装Lombok插件!
2.在项目中导入lombok的jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
3.在实体类加注解
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
什么是JavaBean
JavaBean是一个遵循特定写法的Java类,它通常具有如下特点:
- 这个Java类必须具有一个无参的构造函数
- 属性必须私有化。
- 私有化的属性必须通过public类型的方法暴露给其它程序,并且方法的命名也必须遵守一定的命名规范。
九.多对一处理
多对一:
- 多个学生对应一个老师
- 对于学生这边而言,关联 .. 多个学生,关联一个老师 【多对一】
- 对于老师而言,集合,一个老师,有很多个学生 【一对多】
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,
`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');
1.测试环境搭建:
1.导入lombok
2.导入resource配置文件以及utils工具类 + 新建实体类 Teacher Student
3.建立Mapper接口
4.建立Mapper.xml文件
5.在核心配置文件中绑定注册我们的Mapper接口 (回顾 三.5 映射器中的三种绑定方式)
6.测试查询是否能够成功
2.按照查询嵌套处理
<?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="com.kk.dao.StudentMapper">
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师
3.
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.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 mybatis.teacher where id=#{id}
</select>
</mapper>
3.按照结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from mybatis.student s,mybatis.teacher t
where s.tid=t.id
</select>
<!--直接用sql 查出来是老师,然后因为是老师在进行老师类型的结果集映射-->
<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>
4.回顾Mysql多对一查询方式:
1.子查询
括号里再来一个选择语句
2.联表查询
结果嵌套都属于联表
十.一对多处理
比如:一个老师拥有多个学生!
对于老师而言,就是一对多的联系.
1.环境搭建
与刚才相同
2.实体类
Teacher类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
Student类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
public int tid;
}
1.按照结果嵌套查询
<?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="com.kk.dao.TeacherMapper">
<!--按结果嵌套查询-->
<!--注解param写的tid在这里用到t.id=#{tid}-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from mybatis.student s,mybatis.teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/> <!--column对应查出来的别名tid-->
<result property="name" column="tname"/>
<!--对象 association
集合:collection
javaType:指定的属性的类型
集合中的泛型信息,使用ofType获取(跟Teacher一个道理,只是他是一个集合就需要用ofType获取)
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/> <!--column对应查出来的sid-->
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
2.子查询的方式
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--上面取出来的就是值,用值去对应就可以 所以不需要使用javaType
下面取出来的是集合
-->
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<!--此处的tid由collection处的column传来-->
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid=#{tid}
</select>
3.总结
- 关联: association 【多对一】
- 集合:collection 【一对多】
- javaType ofType
- javaType:用来指定实体类属性的类型
- ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
注意点:
- 保证sql的可读性 (sql复杂的情况下),尽量保证通俗易懂
- 注意一对多和多对一中,属性名和字段的问题!
- 如果不好排查错误,可以使用日志,建议使用Log4j
面试高频
- Mysql引擎
- innoDB底层原理
- 索引
- 索引优化!
十一.动态SQL
我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。
1.环境搭建
创建一个基础工程
1.导包
2.编写配置文件
3.编写实体类
2.IF
IF的作用实现为当查询时候可能会设置条件(单个限制或多个限制),可能不会设置。
IF使得在查询时候可以动态的查询,查询语句不变的情况下,仍然可以实现有限制和无限制的查询。
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
4.编写对应的mapper接口和mapper,xml文件
public interface BlogMapper {
// 插入数据
int addBlog(Blog blog);
/*查询博客*/
List<Blog> queryBlogIF(Map map);
}
<?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="com.kk.dao.BlogMapper">
<insert id="addBlog" parameterType="Blog">
insert into mybatis.blog(id, title, author, create_time, views)
VALUE (#{id}, #{title}, #{author}, #{createTime}, #{views})
</insert>
<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>
</mapper>
public class MyTest {
@Test
public void addBlog() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtils.getId());
blog.setTitle("MyBatisStudy");
blog.setAuthor("KK");
blog.setCreateTime(new Date());
blog.setViews(9999);
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);
}
@Test
public void queryBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","MyBatisStudy");
map.put("author","KK");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
}
3.choose(when,otherwise)
类似switch case ,优先匹配第一个符合的when,但使用choose必须要有一个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>
</mapper>
4.trim(where,set)
4.1where
不再使用1=1,where能根据sql语句数量自动判断是否添加and连接词
<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>
4.2Set
update语句中set中本身 name=#{name},title=#{title} where id=#{id}, 当输入的map中不存在title的修改,会有多余的逗号,而set元素会将多余的逗号自动去除,类似前面where中去除and
<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>
4.3trim
可以自定义sql
5.SQL片段
有的时候,我们可能把一些功能的公共部分的抽取
1.使用SQL标签抽取公共部分
<sql id="if-title-author">
<if test="title !=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
2.在需要使用的的地方用#include标签引用
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
3.注意事项:
- 最好基于单表来定义sql片段!
- 不要存在where标签
6.Foreach![](https://i-blog.csdnimg.cn/blog_migrate/9805730b14d0281634adbb53358aec6b.png)
@Test
public void queryBlogForEach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
ArrayList<Integer> ids = new ArrayList<>();
HashMap map = new HashMap();
ids.add(1);
ids.add(2);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
注意:下述代码中 and (之间要加空格!
<!--select * from blog where 1=1 and (id=1 or id=2 id=3)
我们现在传递一个万能的map 这个map中可以存在一个集合
-->
<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>
所谓的动态SQL,本质还是SQL语句,只是我们在SQL层面,去执行一个逻辑代码
拼接sql语句,只要保证sql的正确性,按照SQL的格式,去排列组合即可
建议:
- 先在mysql写出完整的SQL
- 对应的去修改成为我们的动态sql实现通用
持续提升:
十二.缓存
1.缓存的简介
查询,连接数据库,耗资源!
一次查询的结果,给他暂留在一个可以取到的地方! -->内存
放到内存里的数据 就是缓存,再次查询相同数据的时候,直接走缓存,不需要走数据库了
不用连接数据库,不用拿连接池,不用关闭连接,省很多时间。
1.1什么是缓存【Cache】?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
1.2 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
1.3 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据
2.Mybatis缓存
-
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
-
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
-
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
-
为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
-
3.环境搭建
配置文件(记得绑定mapper) --》 工具类 --》 实体类 --》 dao包 mapper与mapper.xml
测试类记得关闭sqlsession以及提交事务
4.一级缓存
一级缓存也叫本地缓存:
-
与数据库同一次会话期间查询到的数据会放在本地缓存中。
-
以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试步骤:
- 开启日志
- 测试在一个Session中查询两次相同记录
- 查看日志输出
缓存失效的情况:
- 查询不同的东西
- 增删改操作,可能改变原来的数据,会刷新缓存,此时连续两次查找同一语句,比较后结果为false
- 查询不同的Mapper
- 手动清理缓存
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接和关闭连接这个区间
一级缓存相当于一个map
5.二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
-
工作机制
-
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
-
如果当前会话关闭了,这个会话对应的一级缓存就没了;开启全局缓存之后,一级缓存关闭后会自动传给二级缓存
-
新的会话查询信息,就可以从二级缓存中获取内容;
-
不同的mapper查出的数据会放在自己对应的缓存(map)中;
-
步骤:
- 开启全局缓存 【mybatis-config.xml】
<!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的Mapper中开启
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
- 测试
- 问题:只用<cache/>时候,需要将实体类序列化!否则就会报错
Caused by: java.io.NotSerializableException
- 实体类序列化 Implement Serializable
- 问题:只用<cache/>时候,需要将实体类序列化!否则就会报错
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 当会话提交或者关闭的时候,才会提交到二级缓存中
6.缓存原理
- 先在二级缓存里找,再在一级缓存里找。
- 用不同的sqlsession调用同样的数据走的是二级缓存;用相同的Sqlssion找同样的数据走的是一级缓存
7.自定义缓存-ehcache
7.1介绍
Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;
7.2用法
- 导包
<!-- 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.xml中使用对应的缓存即可
<mapper namespace = “org.acme.FooMapper” > <cache type = “org.mybatis.caches.ehcache.EhcacheCache” /> </mapper>
- 编写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"/> <!-- defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。 --> <!-- name:缓存名称。 maxElementsInMemory:缓存最大数目 maxElementsOnDisk:硬盘最大缓存个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 overflowToDisk:是否保存到磁盘,当系统当机时 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 clearOnFlush:内存数量最大时是否清除。 memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。 FIFO,first in first out,这个是大家最熟的,先进先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。 LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 --> </ehcache>
Redis(非关系型数据库)数据库来做缓存! K-V(键值对的形式)
-
自定义缓存了解即可,网上大堆的开源的已经写好的自定义缓存!