MyBatis

第一个MyBatis程序

思路:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试

搭建环境

搭建数据库

create database if not exists mybatis;
use mybatis;
create table user(
id int unsigned auto_increment primary key,
name varchar(20) default null comment '姓名',
password varchar(30) default null comment '密码'
)engine=innodb,default charset=utf8;
insert into user(name,password) values('张三','111111'),('李四','222222'),('王五','333333'),('赵六','444444'),('孙七','555555');


新建项目

  1. 新建一个maven项目
  2. 删除src目录(将该项目作为父工程)
  3. 导入maven依赖
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>


创建一个模块

  1. 编写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> <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/test?characterEncoding=utf8&amp;serverTimeZone=UTC&amp;useSSL=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
  2. 编写mybatis工具类
    package org.example.util; 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 MybatisUtil { private static SqlSessionFactory sqlSessionFactory=null; static { try { //获取sqlSessionFactory对象 String resource="mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } }

编写代码

实体类

package org.example.domain;

public class User {
private int id;
private String name;
private String password;

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}


Dao接口

package org.example.dao;

import org.example.domain.User;

import java.util.List;

public interface UserDao {
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">
<!--namespace绑定一个对应的dao/mapper接口-->
<mapper namespace="org.example.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="org.example.domain.User">
select * from user
</select>
</mapper>


测试

package org.example.dao;

import org.apache.ibatis.session.SqlSession;
import org.example.domain.User;
import org.example.util.MybatisUtil;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

@Test
public void testGetUserList(){
SqlSession sqlSession = null;
try {
//第一步:获取sqlSession对象
sqlSession = MybatisUtil.getSqlSession();
//方式一:getMapper
/*UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}*/
//方式二:不推荐使用
List<User> userList = sqlSession.selectList("org.example.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭sqlSession
sqlSession.close();
}
}
}


CRUD

namespace

namespace:Dao/Mapper接口的全类名

select

选择,查询语句;

  • id:就是对应的namespace中的方法名
  • resultType:sql语句执行的返回值(resultSet中存储的对象)
  • parameterType:参数类型
  1. 编写接口
    //根据id查询用户 User getUserById(int id);
  2. 编写对应的mapper中的sql语句
    <select id="getUserById" resultType="org.example.domain.User" parameterType="int"> select * from user where id=#{id} </select>
  3. 测试
    @Test public void testGetUserById(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); User user = mapper.getUserById(4); System.out.println(user); sqlSession.close(); }

insert

  1. 编写接口
    //增加用户 int addUser(User user);
  2. 编写对应的mapper中的sql语句
    <insert id="addUser" parameterType="org.example.domain.User"> insert into user(name,password) values(#{name},#{password}); </insert>
  3. 测试
    @Test public void testInsert(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); User user = new User(); user.setName("小九"); user.setPassword("777777"); int rows = mapper.addUser(user); System.out.println("受影响的行数:"+rows); //需要提交事务 sqlSession.commit(); sqlSession.close(); }

update

  1. 编写接口
    //修改用户 int updateUser(User user);
  2. 编写对应的mapper中的sql语句
    <update id="updateUser" parameterType="org.example.domain.User"> update user set name=#{name},password=#{password} where id=#{id} </update>
  3. 测试
    @Test public void testUpdateUser(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); User user = mapper.getUserById(7); user.setName("小八"); int rows = mapper.updateUser(user); System.out.println("受影响的行数:"+rows); sqlSession.commit(); sqlSession.close(); }

delete

  1. 编写接口
    //删除用户 int deleteUser(int id);
  2. 编写对应的mapper中的sql语句
    <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete>
  3. 测试
    @Test public void testDeleteUser(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int rows = mapper.deleteUser(7); System.out.println("受影响的行数:"+rows); sqlSession.commit(); sqlSession.close(); testGetUserList(); }

注意:增删改需要提交事务!!!

万能的Map

假设,我们的实体类或者数据库中的表、字段或者参数过多,我们应当考虑使用Map!

接口

int addUser_2(Map<String,Object> map);


mapper文件

<insert id="addUser_2" parameterType="map">
insert into user(name,password) values(#{name},#{password});
</insert>


测试

@Test
public void testAddUser_2(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name","小八");
map.put("password","666666");
int rows = mapper.addUser_2(map);
System.out.println("受影响的行数:"+rows);
sqlSession.commit();
sqlSession.close();
}


Map传递参数,直接在sql中取出key即可!【parameterType="map"】

对象传递参数,直接在sql中取对象的属性即可!【parameterType="Object"】

只有一个基本类型参数的情况下,可以直接在sql取到!

多个参数用Map,或者注解

模糊查询

接口

//模糊查询
List<User> getUserLike(String condition);


mapper文件

//方式一
<select id="getUserLike" resultType="org.example.domain.User" parameterType="string">
select * from user where name like #{condition}
</select>
//方式二(不建议使用)
<select id="getUserLike" resultType="org.example.domain.User" parameterType="string">
select * from user where name like "%"#{condition}"%"
</select>


测试

@Test
public void testGetUserLike(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userLike = mapper.getUserLike("%张%");
for (User user : userLike) {
System.out.println(user);
}
sqlSession.close();
}


配置解析

核心配置文件

  • mybatis-config.xml
  • mybatis的配置文件包含了会深深影响Mybatis行为的属性信息
    configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商表示) mappers(映射器)

环境配置(environments)

MyBatis可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境

学会使用配置多套运行环境

MyBatis默认的事务管理器就是JDBC,连接池:POOLED

<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/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>


属性(properties)

我们可以通过properties属性来实现引用配置文件

这些属性都是可外部配置且动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素传递

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
username=root
password=123456


mybatis配置文件属性顺序

MyBatis详解_配置文件

引入外部配置文件

<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="111111"/>
</properties>


  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的

类型别名(typeAliases)

  • 类型别名是为Java类型设置一个短的名字
  • 存在的意义仅在于用来减少类完全限定名的冗余
<!--类型别名-->
<typeAliases>
<typeAlias type="org.example.domain.User" alias="user"/>
</typeAliases>


也可以指定一个包名,MyBatis会在包名下面搜索需要的Java Bean,比如:扫描实体类的包,它的默认别名就为这个类的类名首字母小写!

<!--类型别名-->
<typeAliases>
<package name="org.example.domain"/>
</typeAliases>


在实体类比较少的时候,使用第一种方式

如果实体类十分多,建议使用第二种

第一种可以自定义别名,第二种不行,如果非要改,需要在实体上增加注解

@Alias("user")
public class User{

}


设置

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。

目前记住以下四个即可!

设置名

描述

有效值

默认值

cacheEnabled

全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。

true | false

true

lazyLoadingEnabled

延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 ​​fetchType​​ 属性来覆盖该项的开关状态。

true | false

false

mapUnderscoreToCamelCase

是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。

true |false

False

logImpl

指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

SLF4J |LOG4J |LOG4J2 |JDK_LOGGING |COMMONS_LOGGING |STDOUT_LOGGING |NO_LOGGING

未设置

其他配置

知道即可,不用了解!

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins插件
  • mybatis-generator-core
  • mybatis-plus
  • 通用mapper

映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件:

方式一:(推荐使用)

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>


方式二:使用class文件绑定注册

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper class="org.example.mapper.UserMapper"/>
</mappers>


注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

方式三:使用扫描包进行注入绑定

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<package name="org.example.mapper"/>
</mappers>


注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

声明周期和作用域

生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 一旦创建了SqlSessionFactory,就不再需要它了
  • 局部变量

SqlSessionFactory:

  • 说白了就是可以想象为:数据库连接池
  • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • 因此SqlSessionFactory的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式

SqlSession:

  • 连接到连接池的一个请求
  • SqlSession的实例不是线程安全的,因此不能被共享,所以它的最佳的作用域是请求或方法作用域
  • 用完之后需要赶紧关闭,否则资源被占用!

解决属性名和字段名不一致的问题

问题

数据库字段名称

MyBatis详解_缓存_02

Java实体类字段

public class User{
private int id;
private String name;
private String pwd;
}


查询结果

MyBatis详解_sql_03

解决方法

  • 起别名
<select id="getUserLike" resultType="user" parameterType="string">
select id,name,password pwd from user where name like #{condition}
</select>


resultMap

结果集映射

//user表字段
id name password
//user实体类属性
id name pwd
<!--结果集映射-->
<resultMap id="UserMap" type="user">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="pwd"/>
</resultMap>
<!--<select id="getUserLike" resultType="user" parameterType="string">-->
<select id="getUserLike" resultMap="UserMap" parameterType="string">
select * from user where name like #{condition}
</select>


  • ResultMap元素是MyBatis中最重要最强大的元素
  • ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了
  • ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们
  • 如果世界总是这么简单就好了

日志

日志工厂

如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!

曾经:sout、debug

现在:日志工厂

MyBatis详解_mysql_04

  • SLF4J
  • LOG4J(掌握)
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING(掌握)
  • NO_LOGGING

在mybatis中具体使用哪一个日志实现,在设置中设定!

STDOUT_LOGGING标准日志输出

在mybatis核心配置文件中,配置我们的日志!

<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>


MyBatis详解_mysql_05

Log4j

什么是log4j?

  • log4j是Apache的一个开源项目,通过使用log4j,我们可以控制日志信息输送的目的地是控制台、文件、gui组件
  • 我们也可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
  1. 先导入log4j的jar包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>


  1. log.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/mybatis-03.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


  1. 配置log4j为日志的实现
<settings>
<!--log4j日志实现-->
<setting name="logImpl" value="LOG4J"/>
</settings>


  1. log4j的使用,直接测试运行

MyBatis详解_缓存_06

简单使用

  1. 在要使用的log4j的类中,导入包:import org.apache.log4j.Logger;
  2. 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserMapper.class);


  1. 日志级别
logger.info("info:进入了testLog4j方法");
logger.debug("debug:进入了testLog4j方法");
logger.error("error:进入了testLog4j方法");


分页

使用limit分页

# 语法:select * from user limit startIndex,pageSize;
select * from user limit 3;# [0,3)


使用mybatis实现分页,核心sql

  1. 接口
//分页
List<User> getUserPage(Map<String,Integer> map);


  1. Mapper.xml
<select id="getUserPage" resultType="user" parameterType="map">
select * from user limit #{startIndex},#{pageSize}
</select>


  1. 测试
@Test
public void testUserPage(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Integer> map=new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userPage = mapper.getUserPage(map);
for (User user : userPage) {
System.out.println(user);
}
sqlSession.close();
}


RowBounds分页

不再使用sql实现分页

  1. 接口
List<User> getUserByRowBounds();


  1. mapper.xml
<select id="getUserByRowBounds" resultType="user">
select * from user
</select>


  1. 测试
@Test
public void testGetUserByRowBounds(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
//RowBoudns实现
RowBounds rowBounds = new RowBounds(0, 2);

//通过Java代码层面来实现分页
List<User> userList = sqlSession.selectList("org.example.mapper.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}


分页插件

MyBatis详解_java_07

​MyBatis 分页插件 PageHelper​

ps:这里不做讲解,可到官网查看

使用注解开发

面向接口编程

  • 大家之前都学过面向对象编程,也学过接口,但在真正的开发中,很多时候我们会选择面向接口编程
  • 根本原因:解耦,可拓展、提高复用,在分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易规范性更好
  • 在一个面向对象的系统中,系统的各种是由许许多多的不同对象协作完成的,在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了
  • 而各个对象之间的协作关系则称为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
  • 接口的本身反映了系统设计人员对系统的抽象理解
  • 接口应有两类:
  • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class)
  • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface)
  • 一个个体可能有多个抽象面,抽象体与抽象面是有区别的

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
  • 接口设计与非接口设计是指复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是系统整体的架构

使用注解开发

  1. 注解在接口上实现
//查询全部用户
@Select("select * from user")
List<User> getUserList();


  1. 需要在核心配置文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="org.example.mapper.UserMapper"/>
</mappers>


  1. 测试
@Test
public void testGetUserList(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
//底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}


本质:反射机制实现

底层:动态代理

CRUD

  1. 编写接口
//如果方法存在多个参数,参数面前必须加上@Param注解
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);

@Insert("insert into user(name,password) values(#{name},#{password})")
int addUser(User user);

@Update("update user set name=#{name},password=#{password} where id=#{id}")
int updateUser(User user);

@Delete("delete from user where id=#{id}")
int deleteUserById(int id);


  1. 绑定接口
<!--绑定接口-->
<mappers>
<mapper class="org.example.mapper.UserMapper"/>
</mappers>


  1. 测试
@Test
public void testDeleteUserById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int rows = mapper.deleteUserById(1);
System.out.println("受影响的行数:"+rows);
testGetUserList();
sqlSession.close();
}

@Test
public void testUpdateUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
int rows = mapper.updateUser(user);
System.out.println("受影响的行数:"+rows);
sqlSession.commit();
sqlSession.close();
}

@Test
public void testAddUser(){
User user = new User();
user.setName("小九");
user.setPassword("777777");
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.addUser(user);
sqlSession.commit();
System.out.println("受影响的行数:"+i);
testGetUserList();
sqlSession.close();
}

@Test
public void testGetUserById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
}


注意:我们必须要将接口注册绑定到我们的核心配置文件中

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
  • 我们在sql中引用的就是我们这里的@Param("uid")中设置的属性名

#{}与${}的区别:可以简单理解为#{}可以防止sql注入,${}不可以

Lombok

MyBatis详解_mysql_08

​Project Lombok​

使用步骤:

  1. 在IDEA中安装Lombok插件
  2. 在项目中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>


  1. 在实体类上加注解即可
@Data
public class User{}


注解

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor(全参构造), @RequiredArgsConstructor and @NoArgsConstructor(无参构造)
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data(get、set、toString、hashCode、equals、无参构造)
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
@ExtensionMethod (Experimental, activate manually in plugin settings)


多对一处理

sql

create table teacher(
id int unsigned auto_increment primary key,
name varchar(30) comment '姓名'
)engine=innodb,default charset=utf8;
insert into teacher(name) values('秦老师');
create table student(
id int unsigned auto_increment primary key,
name varchar(30) comment '姓名',
tid int unsigned,
foreign key(tid) references teacher(id)
)engine=innodb,default charset=utf8;
insert into student(name,tid) values('张三',1),('李四',1),('王五',1),('赵六',1),('孙七',1);


测试环境搭建

  1. 导入lombok
  2. 新建实体类Teacher、Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!(方式很多,随心选)
  6. 测试查询是否能够成功

按照查询嵌套处理

<select id="getAllStudent" resultMap="studentMap">
select * from student
</select>
<resultMap id="studentMap" type="student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性我们需要单独处理 对象:association 集合:collection-->
<association property="teacher" column="tid" javaType="teacher" select="getTeacherByTid"/>
</resultMap>
<select id="getTeacherByTid" resultType="teacher" parameterType="int">
select * from teacher where id=#{tid}
</select>


按照结果嵌套处理

<select id="getAllStudent" resultMap="studentMap">
select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id
</select>
<resultMap id="studentMap" type="student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>


回顾mysql多对一查询方式:

  • 子查询
  • 联表查询

一对多处理

环境搭建

@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}


按照结果嵌套处理

<select id="getTeacherById" resultMap="teacherMap" parameterType="int">
select s.id sid,s.name sname,t.id tid,t.name tname from teacher t,student s where t.id=s.tid and t.id=#{tid}
</select>
<resultMap id="teacherMap" type="teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection
javaType="" 指定属性的类型
集合中的泛型信息,我们使用ofType获取-->
<collection property="students" ofType="student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>


按照查询嵌套处理

<select id="getTeacherById" resultMap="teacherMap">
select * from teacher where id=#{tid}
</select>
<resultMap id="teacherMap" type="teacher">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="student" select="getStudentByTid" column="id"/>
</resultMap>
<select id="getStudentByTid" resultType="student" parameterType="int">
select * from student where tid=#{tid}
</select>


小结

  1. 关联 - association(多对一)
  2. 集合 - collection(一对多)
  3. javaType & ofType
  1. javaType:用来指定实体类中属性的类型
  2. ofType:用来指定映射到集合中的泛型的类型

​动态sql​

什么是动态sql:动态sql就是指根据不同的条件生成不同的sql语句

搭建环境

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;


创建一个一个基础工程

  1. 导包
  2. 编写配置文件
  3. 编写实体类
@Data
@ToString
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}


  1. 编写实体类对应Mapper接口和Mapper.xml文件

if

<select id="getBlogIf" 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>


trim(where,set)

where

<select id="getBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<when test="views!=null">
and views>#{views}
</when>
</choose>
</where>
</select>


set

<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
<if test="views!=null">
views=#{views}
</if>
</set>
where id=#{id}
</update>


所谓动态sql,本质还是sql语句,只是我们可以在sql层面,去执行一个逻辑代码

sql片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

  1. 使用sql标签抽取公共的部分
<sql id="if-title-author-views">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
<if test="views!=null">
and views=#{views}
</if>
</sql>


  1. 在需要使用的地方使用include标签引用即可
<select id="getBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author-views"/>
</where>
</select>


注意事项

  • 最好基于单表来定义sql片段
  • 不要存在where标签

foreach

<select id="getBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>


动态sql就是在拼接sql语句,我们只要保证sql的正确性,按照sql格式,去排列组合就可以了

建议:

  • 现在mysql中写出完整的sql,再对应的去修改成为我们的动态sql实现通用即可

​mybatis – MyBatis 3 | 动态 SQL​

​缓存​

简介

连接数据库耗资源!一次查询的结果,给它暂存到一个可以直接取到的地方(内存/缓存),当我们再次查询相同的数据时,直接走缓存,就不用走数据库了

  1. 什么是缓存(Cache)
  • 存在内存中的临时数据
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
  1. 为什么使用缓存?
  • 减少和数据库的交互次数,减少系统开销,提高系统效率
  1. 什么样的数据能使用缓存?
  • 进场查询并且不经常改变的数据

mybatis缓存

  • mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
  • mybatis系统中默认设置了两级缓存:一级缓存和二级缓存
  • 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
  • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
  • 为了提高扩展性,mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存

一级缓存

  • 一级缓存也叫本地缓存:
  • 与数据库同一次会话期间查询到的数据会放在本地缓存中
  • 以后如果需要获取相同的数据,直接从缓存中拿,不需要再去查询数据库

测试步骤:

  1. 开启日志
  2. 测试在一个Session查询两次相同记录
  3. 查询日志输出

MyBatis详解_mysql_09

缓存失效的情况:

  1. 查询不同的东西
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
  3. 查询不同的Mapper.xml
  4. 手动清理缓存

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
  • 一个会话查询一条数据,这个数据就会被放在当前会话的以及缓存中
  • 如果当前会话关闭了,这个会话对应的以及缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
  • 新的会话查询信息,就可以从二级缓存中获取内容
  • 不同的mapper查出的数据会放在对应的缓存(map)中

步骤:

  1. 开启全局缓存
<!--显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>


  1. 在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>


也可以自定义参数

<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>


  1. 测试
@Test
public void testCache(){
SqlSession sqlSession1 = MybatisUtil.getSqlSession();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = mapper1.getUserById(1);
sqlSession1.close();

SqlSession sqlSession2 = MybatisUtil.getSqlSession();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.getUserById(1);
sqlSession2.close();

System.out.println(user1);
System.out.println(user2);
System.out.println(user1==user2);
}


小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓存中

缓存原理

MyBatis详解_java_10


作者:(x²+y²-1)³=x²y³


​ ​


-------------------------------------------

个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!