一. Mybatis简介
1.1 什么是Mybatis
- MyBatis 是apache一款优秀的持久层框架(若包导错, 检查包名是否apache)
- 它支持自定义 SQL、存储过程以及高级映射
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects, 普通老式 Java 对象)为数据库中的记录。
- 现迁移到GitHub
1.2 如何获得Mybatis
Maven仓库:https://mvnrepository.com/
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
GitHub:https://github.com/mybatis/mybatis-3
官方文档:https://mybatis.org/mybatis-3/zh/index.html
1.3 持久化
存储在内存的数据断电即失, 数据库/IO文件可以持久化存储. 持久化就是将程序的数据在持久状态和瞬时状态转化的过程.
持久化原因. 内存太贵, 某些数据不能丢失.
持久层
如Dao层, Service层, Controller层. 完成持久化工作的代码块.
为什么需要Mybatis
- 方便, 帮助程序员将数据存入到数据库中;
- 传统的jdbc代码太复杂了,简化代码,形成框架。----自动化
- 不使用MyBatis也可以,使用则更容易上手;
Mybatis的优点
- 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的ORM字段关系映射。( ORM, Object Relational Mapping 的缩写,译为“对象关系映射”, 它解决了对象和关系型数据库之间的数据交互问题)
- 提供对象关系映射标签,支持对象关系组建维护。
- 提供xml标签,支持编写动态sql。
二. Mybatis入门
思路. 搭建环境, 导入Mybatis, 编写代码, 测试.
2.1 入门案例
搭建数据库
新建mybatis数据库创建user表, 添加数据.
-- 创建数据库用于学习mybatis
CREATE DATABASE mybatis CHARSET utf8 COLLATE utf8_general_ci;
USE mybatis;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`pwd` VARCHAR(20) NOT NULL,
PRIMARY KEY(`id`)
)ENGINE = INNODB CHARACTER SET = utf8 COLLATE = utf8_general_ci;
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES
(1, 'jack', '123456'),
(2, 'tom', '123456'),
(3, 'lily', '123456');
搭建项目
新建项目, 编写工具依赖.
- 搭建Maven普通项目, 添加maven依赖;(学习时, 删除src, 建立多个module)
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<!--在build中配置resources , 来防止我们资源导出失败的问题. 默认只有resources下的资源能够导出-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
- 在resources文件夹下, 编写mybatis核心配置文件. mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册
resource对应的填地址
-->
<mappers>
<mapper resource="com/lqz/dao/UserMapper.xml"/>
</mappers>
</configuration>
- 在Java目录utils包下, 编写mybatis工具类.
package com.lqz.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;
/**
* describe:
*
* @author liqize
* @version 1.0
*/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用mybatis获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
return sqlSessionFactory.openSession();
}
}
编写代码
实体类
package com.lqz.pojo;
/**
* describe:
*
* @author liqize
* @version 1.0
*/
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接口. 这里改为Mapper接口
public interface UserMapper {
List<User> getUserList();
}
接口实现类改为UserMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个Mapper接口-->
<mapper namespace="com.lqz.dao.UserMapper">
<select id="getUserList" resultType="com.lqz.pojo.User">
select * from user
</select>
</mapper>
回到resources文件夹下, mybatis的核心配置文件, 添加注册. mybatis-config.xml
<mappers>
<mapper resource="com/lqz/dao/UserMapper.xml"/>
</mappers>
测试
在test文件夹下, 编写相应的测试类.
public class UserDaoTest {
@org.junit.Test
public void getUserList(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.从接口获得mapper,并执行对应的方法
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
//方式二.知道即可,不推荐使用.
//List<User> userList1 = sqlSession.selectList("com.qjd.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//3.关闭sqlSession
sqlSession.close();
}
}
2.2 CRUD
实现增删改查
1.接口.UserMapper
public interface UserMapper {
//查
List<User> getUserList();
User getUserById(int id);
//增
int addUser(User user);
//删
int deleteUser(int id);
//改
int modifyUser(User user);
}
2.映射.UserMapper.xml
<!--namespace绑定一个Mapper接口-->
<mapper namespace="com.lqz.dao.UserMapper">
<!--
id就是对应的namespace中的方法名
resultType就是Sql语句执行的返回类型
parameterType就是参数类型, int可以不写
-->
<select id="getUserList" resultType="com.lqz.pojo.User">
select * from user
</select>
<select id="getUserById" parameterType="int" resultType="com.lqz.pojo.User">
select * from user where id = #{id}
</select>
<insert id="addUser" parameterType="com.lqz.pojo.User">
insert into mybatis.user(id, name, pwd) values (#{id}, #{name}, #{pwd})
</insert>
<update id="deleteUser" parameterType="int">
delete from user where id = #{id}
</update>
<update id="modifyUser" parameterType="com.lqz.pojo.User">
update user set name = #{name}, pwd = #{pwd} where id = #{id}
</update>
</mapper>
3.测试
public class UserDaoTest {
@Test
public void getUserList(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.从接口获得mapper,并执行对应的方法
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
//方式二.知道即可,不推荐使用.
//List<User> userList1 = sqlSession.selectList("com.qjd.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//3.关闭sqlSession
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.addUser(new User(4, "john", "111222"));
System.out.println(count);
//增删改需要提交业务
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.deleteUser(4);
System.out.println(count);
//增删改需要提交业务
sqlSession.commit();
sqlSession.close();
}
@Test
public void modifyUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.modifyUser(new User(4, "zero", "111222"));
System.out.println(count);
//增删改需要提交业务
sqlSession.commit();
sqlSession.close();
}
}9
2.3 Map
应用场景. 当我们传入的字段是几个参数时, 考虑使用Map.(也可以考虑注解)
- map传递的参数, 直接在sql中取出key即可;
- 对象传递的参数, 直接在sql中取出属性即可;
- 只有一个基本类型参数的情况下, 可以直接在sql中取到;
示例. 如根据用户名和密码查询.
UserMapper
public interface UserMapper {
//查
User getUserForLogin(Map map);
}
UserMapper.xml
<select id="getUserForLogin" parameterType="map" resultType="com.lqz.pojo.User">
select * from user where name = #{name} and pwd = #{pwd}
</select>
测试
@Test
public void getUserForLogin(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "jack");
map.put("pwd", "123456");
User user = mapper.getUserForLogin(map);
System.out.println(user);
sqlSession.close();
}
2.4 模糊查询
两种方式. 可以避免sql注入.
1.java代码执行的时候,传递通配符% %
List<User> userList = mapper.getUserLike("%李%");
2.在sql拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%"
三. 配置解析
3.1 核心配置文件
核心配置文件mybatis-config.xml
- 按照如下位置写配置文件顺序 (若忘记了, 可写一个测试一下, 会报错)
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
环境配置
environment
- Mybatis可以配置成适应多种环境; 虽然可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境;
- Mybatis默认的事务管理器就是JDBC,连接池:POOLED
<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=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type=""></transactionManager>
<dataSource type=""></dataSource>
</environment>
</environments>
属性
properties. 我们可以通过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=123456
在核心配置文件中引入mybatis-config.xml
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="12345"/>
</properties>
类型别名
typeAliases. 类型别名是为Java类型设置一个短的名字, 存在的意义在于减少类完全限定名的冗余.
<typeAliases>
<typeAlias type="com.lqz.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis会在包名下面搜索需要的JavaBean,比如: 扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!
<typeAliases>
<package name="com.lqz.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式; 如果实体类十分多,建议使用第二种;
- 第一种可以DIY别名,第二种则不行,如果非要改,需要在实体上增加注解
- 别名不区分大小写, 但是为了应对原始类型命名的重复, 基本数据类型前加下划线;(参考官方文档)
_int -> int
int -> Integer
设置
settings. 是MyBatis中极为重要的调整设置,它们会改变MyBatis的运行时行为。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zbupvo3i-1672735552218)(mybatis.assets/image-20221208093416460.png)]
映射器
MapperRegistry. 注册绑定我们的Mapper文件.
方式1. 使用resource绑定xml文件.
<mappers>
<mapper resource="com/lqz/dao/UserMapper.xml"/>
</mappers>
方式2. 使用class文件绑定注册, 同时绑定接口和xml文件. 在Java开发中最常使用.
- 接口和它的Mapper配置文件必须同名!
- 接口和它的Mapper配置文件必须在同一个包下(指的是最终生成的在同一个文件夹下)!
<mappers>
<mapper class="com.lqz.dao.UserMapper"/>
</mappers>
方式3. 使用使用扫描包进行注入绑定.
- 接口和它的Mapper配置文件必须同名!
- 接口和它的Mapper配置文件必须在同一个包下!
<mappers>
<package name="com.lqz.dao"/>
</mappers>
其它配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
3.2 生命周期和作用域
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QzzxZymx-1672735552219)(mybatis.assets/image-20221208101042538.png)]
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了;
- 局部变量;
SqlSessionFactory:
- 说白就是可以想象为:数据库连接池。
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- SqlSessionFactory 的最佳作用域是应用作用域。
- 最简单的就是使用单例模式或者静态单例模式。
SqlSession:
- 连接到连接池的一个请求!
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完后需要赶紧关闭,否则资源被占用!
3.3 mybatis执行的详细流程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rDznPTFm-1672735552220)(mybatis.assets/image-20221208145930451.png)]
四. 日志
4.1 日志工厂
如果一个数据库操作出现异常, 我们需要排错, 日志是最好的助手.
曾经的工具. sout, dabug.
现在的工具. 日志工厂. 可以清楚看到程序是如何一步步走的.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qEQTw5gv-1672735552220)(mybatis.assets/image-20221208104509395.png)]
- SLF4J
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING【掌握】
- NO_LOGGING
在Mybatis中具体使用哪一个日志实现,在设置中设定!
4.2 STDOUT_LOGGING
在mybatis-config.xml核心配置文件中,配置我们的日志!
<settings>
<!--千万注意,一个大小写,一个空格都别写错. 固定死的,推荐复制-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
从日志文件中可以清楚看到, 程序是如何一步步走的.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7xy6mbX1-1672735552221)(mybatis.assets/image-20221208105055828.png)]
4.3 Log4j
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件.
- 我们也可以控制每一条日志的输出格式;
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1.先在pom.xml文件中导入log4j的依赖包
<dependencies>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
2.在resources文件夹下建立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/lqz.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.在mybatis-config.xml核心配置文件中,配置log4j为日志的实现!
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
4.Log4j的使用,直接测试运行
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MTcBjhyo-1672735552221)(mybatis.assets/image-20221208110646814.png)]
简单使用
1.在要使用Log4j的测试类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
public class LogInfo {
Logger logger = Logger.getLogger(LogInfo.class);
@Test
public void log(){
//日志级别
logger.info("info: 测试log4j");
logger.debug("debug: 测试log4j");
logger.error("error:测试log4j");
}
}
3.之后可在log文件夹中查看日志文件信息. 会提醒你安装log相关插件, 安装后看起来更简单.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0dQOsZeJ-1672735552221)(mybatis.assets/image-20221208111643862.png)]
五. 常见问题
5.1 属性名和字段名不一致问题
举例
数据库中字段
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ACTPC2th-1672735552222)(mybatis.assets/image-20221208102806217.png)]
项目中的实体类
public class User {
private int id;
private String name;
private String password;
}
映射UserMapper.xml
<select id="getUserList" resultType="User">
select * from user
</select>
测试结果
很奇怪, 我的就没问题, 难道mybatis已经如此智能识别, 自动匹配了吗? 只有一个, 会自动识别并匹配.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oxN1kX4r-1672735552222)(mybatis.assets/image-20221208103402656.png)]
解决方案1. 起别名
<select id="getUserById" parameterType="int" resultType="user">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
解决方案2. resultMap
resultMap 元素是 MyBatis 中最重要最强大的元素。
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
- ResultMap 的优秀之处——你完全可以不用显式地配置它们。
<!--column 数据库中的字段
property 实体类中的属性
-->
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserList" resultMap="UserMap">
select * from user
</select>
5.2 分页
分页方便展示.
核心sql. limit
SELECT * from user limit startIndex,pageSize
SELECT * from user limit 3 #[0,n]
使用mybatis实现分页
1.接口
List<User> getUserByLimit(Map<String, Integer> map);
2.Mapper.xml
<select id="getUserByLimit" parameterType="map" resultType="User">
select * from user limit #{startIndex},#{pageSize}
</select>
3.测试
public class UserDaoTest {
@Test
public void getUserListByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex", 0);
map.put("pageSize", 2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
使用RowBounds分页
表面不再使用SQL实现分页, 底层还是sql语句limit的封装.
1.接口
List<User> getUserByRowBounds();
2.Mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
3.测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(0, 2);
//通过java代码层面实现分页
List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
分页插件
mybatis分页插件, PageHelper https://pagehelper.github.io/
百度一堆教程. 了解即可, 使用时需要知道这是什么东西.
六. 使用注解开发
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法;
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现;
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构;
6.1 面向接口编程
之前学过面向对象编程,也学习过接口,但在真正的开发中,很多时候会选择面向接口编程。
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好.
- 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了, 而各个对象之间的协作关系则成为系统设计的关键。
- 小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
6.2 使用注解开发示例
1.注解在UserMapper接口上实现,并删除UserMapper.xml文件(下面会绑定, 这个不需要了)
@Select("select * from user")
List<User> getUserList();
2.需要在mybatis-config.xml核心配置文件中绑定接口
<mappers>
<mapper class="com.lqz.dao.UserMapper"/>
</mappers>
3.测试
public class UserDaoTest {
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
本质:反射机制实现
底层:动态代理!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dkuclVax-1672735552223)(mybatis.assets/image-20221208143903795.png)]
6.3 CRUD
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议都加上!
- 我们在SQL中引用的就是我们这里的@Param(“”)中设定的属性名!
#{}和${}区别. 建议使用前者, 后者拼接sql可能出现sql注入的问题.
1.在MybatisUtils工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession(){
//设置事务自动提交
return sqlSessionFactory.openSession(true);
}
2.编写接口, 增加注解. 记得写完后在mybatis-config.xml核心配置文件中绑定接口.
public interface UserMapper {
//查
@Select("select * from user")
List<User> getUserList();
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
User getUserForLogin(Map map);
List<User> getUserLike(String keyword);
//增
@Insert("insert into user(id, name, pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
//删
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") int id);
//改
@Update("update user set name=#{name}, pwd=#{pwd} where id=#{id}")
int modifyUser(User user);
}
3.测试
@Test
public void modifyUserTest(){
//注意. 需要MybatisUtils中设置事务自动提交
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// int count = mapper.addUser(new User(5, "charm", "999999"));
// int count = mapper.modifyUser(new User(5, "adorable", "123456"));
int count = mapper.deleteUser(5);
if (count > 0){
System.out.println("success!");
}
sqlSession.close();
}
6.4 Lombok工具
简化开发的工具. 使用注解在实体类上添加构造, set, get等方法.
使用步骤
- 在IDEA中添加Lombok插件. 搜索并下载;
- 在项目导入Lombok的jar包;
- 在实体类上添加注解即可使用
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
在实体上添加注解. 三个放一起, 有/无构造, get和set方法都有了.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
注解说明
@Data //无参构造、get、set、toString、hashCode、equals
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
@EqualsAndHashCode
@ToString
@Getter and @Setter
七. 联表查询
7.1 环境搭建
联表查询
- 多对一. 多个学生对应一个老师. 关联
- 一对多. 一个老师对应多个学生. 集合
SQL建表
# 一对多,多对一
/*
Table structure for teacher
id
name
*/
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`(
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE = INNODB CHARACTER SET = utf8 COLLATE = utf8_general_ci;
INSERT INTO teacher(`id`, `name`) VALUES(1, '秦老师');
SELECT * FROM teacher;
/*
Table structure for student
id
name
tid teacher id
*/
DROP TABLE IF EXISTS `student`;
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即可对外键重命名
CONSTRAINT `fktid` FOREIGN KEY(`tid`) REFERENCES `teacher`(`id`)
)ENGINE = INNODB CHARACTER SET utf8 COLLATE = utf8_general_ci;
INSERT INTO `student`(`id`, `name`, `tid`) VALUES
(1, 'jack', 1),
(2, 'tom', 1),
(3, 'john', 1),
(4, 'lucy', 1);
SELECT * FROM `student`;
测试环境搭建
- 导入Lombok
- 新建实体类Teacher,Student
- 建立Mapper接口
- 建立Mapper.XML文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】
- 测试查询是否能够成功!
配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--外部配置文件-->
<properties resource="db.properties">
<!--这里可以增加一些属性,优先级低于 db.properties-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="pwd" value="12345"/>-->
</properties>
<settings>
<!--日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<!-- <typeAlias type="com.lqz.pojo.User" alias="User"/>-->
<typeAlias type="com.lqz.pojo.Teacher" alias="Teacher"/>
<typeAlias type="com.lqz.pojo.Student" alias="Student"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--读取 db.properties 中配置-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册Mapper-->
<mappers>
<mapper class="com.lqz.dao.TeacherMapper"/>
<mapper class="com.lqz.dao.StudentMapper"/>
</mappers>
</configuration>
7.2 多对一
需求分析. 查询学生信息, 显示学生的老师姓名.
实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
Mapper接口
public interface TeacherMapper {
@Select("select * from teacher where id = #{id}")
Teacher getTeacherById(@Param("id") int id);
}
public interface StudentMapper {
//按照结果嵌套处理
List<Student> getStudentList01();
//按照查询嵌套处理
List<Student> getStudentList02();
}
Mapper.xml配置文件
- 在resources目录下建包, 注意使用 / 分割, 否则无法找到.
TeacherMapper.xml. 使用注解查询, 此处映射没写.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lqz.dao.TeacherMapper">
</mapper>
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个Mapper接口-->
<mapper namespace="com.lqz.dao.StudentMapper">
<!--方式1. 按照查询嵌套-->
<select id="getStudentList01" resultMap="StudentTeacher01">
select * from student
</select>
<resultMap id="StudentTeacher01" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
</resultMap>
<select id="getTeacherById" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
<!--方式2. 按照结果嵌套处理-->
<select id="getStudentList02" resultMap="StudentTeacher02">
<!--若不写tid, Teacher对象id一列会为空, 视业务是否需要而定-->
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="StudentTeacher02" type="Student">
<!--property 类的属性, column取出的字段-->
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>
test
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudentList02();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
7.3 一对多
需求分析. 查询老师信息, 显示所有.
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> studentList;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
Mapper接口
public interface TeacherMapper {
//按照查询嵌套处理
Teacher getTeacherById01(@Param("id") int id);
//按照结果嵌套查询
Teacher getTeacherById02(@Param("id") int id);
}
public interface StudentMapper {
//根据tid查询学生
List<Student> getStudentListByTid(int tid);
}
Mapper.xml配置文件
- 在resources目录下建包, 注意使用 / 分割, 否则无法找到.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个Mapper接口-->
<mapper namespace="com.lqz.dao.StudentMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lqz.dao.TeacherMapper">
<!--按照查询嵌套处理-->
<select id="getTeacherById01" resultMap="TeacherStudent01">
select * from teacher where id = #{id}
</select>
<resultMap id="TeacherStudent01" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="studentList" javaType="ArrayList" ofType="Student" select="getStudentListByTid" column="id"/>
</resultMap>
<select id="getStudentListByTid" resultType="Student">
select * from student where tid = #{tid}
</select>
<!--按照结果嵌套处理-->
<select id="getTeacherById02" resultMap="TeacherStudent02">
select t.id tid, t.name tname, s.id sid, s.name sname
from student s, teacher t
where s.tid = t.id and t.id = #{id}
</select>
<resultMap id="TeacherStudent02" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="studentList" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
test
@Test
public void getTeacher(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacherById02(1);
System.out.println(teacher);
sqlSession.close();
}
小结
- 关联-association【多对一】
- 集合-collection【一对多】
- javaType & ofType
- javaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
注意点:
- 保证SQL的可读性,尽量保证通俗易懂.
- 注意一对多和多对一中,属性名和字段的问题!
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
- 按照实际业务需要使用, 但sql比较容易调试, 推荐写长sql语句, 其它映射即可.
八. 动态SQL
动态SQL就是根据不同的条件生成不同的SQL语句.
<!--重点掌握四种-->
if
choose (when, otherwise)
trim (where, set)
foreach
搭建环境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
INSERT INTO blog (id, title, author, create_time, views) VALUE
('1','java','hsp','1999-10-1','10'),
('2','MySQL','hsp','2009-10-1','15'),
('3','JavaWeb','kss','2019-10-1','40'),
('4','spring','kss','2029-10-1','20');
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--外部配置文件-->
<properties resource="db.properties">
<!--这里可以增加一些属性,优先级低于 db.properties-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="pwd" value="12345"/>-->
</properties>
<settings>
<!--日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--开启驼峰命名自动映射. 如表中字段名user_name到属性名userName的映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<typeAlias type="com.lqz.pojo.Blog" alias="Blog"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--读取 db.properties 中配置-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册Mapper-->
<mappers>
<mapper class="com.lqz.dao.BlogMapper"/>
</mappers>
</configuration>
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog implements Serializable {
private int id;
private String title;
private String author;
//注意util包下.
//注意属性名与表的字段不一致,在配置中设置.
private Date createTime;
private int views;
}
8.1 if
BlogMapper.java
//查. 动态SQL IF
List<Blog> queryBlogIF(@Param("title") String title, @Param("author") String author);
BlogMapper.xml
<mapper namespace="com.lqz.dao.BlogMapper">
<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>
</mapper>
where标签
将上面的where 1=1
换成了where标签
。有if
取值为真,才会去插where
子句,且若语句的开头为OR或AND
,会将其自动去除
<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>
8.2 choose
在choose标签
里面选择一个执行,优先级与顺序有关,类似于 if-else if-else
或switch
语句
<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>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
8.3 set
用于修改表
<update id="modifyBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
and author = #{author}
</if>
</set>
where id = #{id}
</update>
where和set, 都是trim类型语句(可以自定义), 可以根据sql内容动态增减逗号, and等.
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
8.4 foreach
动态sql的另一个常见应用场景是对集合进行遍历, 尤其是在构建in条件语句的时候.
BlogMapper.xml
<!--
select * from blog where (id=1 or id=2 or id=3)
-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
test
@Test
public void selectBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
map.put("ids", ids);
List<Blog> blogList = mapper.queryBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
8.5 SQL片段
将一部分功能抽取出来, 方便复用.
1.使用SQL标签抽取公共的部分.
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
2.在需要的地方使用include标签引用
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项
- 最好基于单表定义SQL片段.(即公共部分写简单点, 写if判断即可)
- where, set等动态修改SQL的语句, 不要放在公共部分;
小结
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了。
建议:先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可!
九. 缓存
9.1 简介
缓存. 存在内存中的临时数据. 将用户经常查询的数据在在内存(缓存)中, 用户查询数据就不用从磁盘上(关系型数据库查询文件), 而是从缓存中查询, 从而提高查询效率, 解决高并发系统的性能问题.
为什么使用缓存
- 减少和数据库交互的次数, 减少系统开销, 提高系统效率;
什么样的数据能使用缓存
- 经常查询且不需要改变的数据;
9.2 Mybatis缓存
Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存.
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
- 为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XnzIV0WH-1672735552224)(MyBatis.assets/image-20221213113706190.png)]
查询流程
- 先看二级缓存(namespace级别)中是否有;
- 再看一级缓存(SqlSession内部)中是否有;
- 查询数据库
9.3 一级缓存
一级缓存也叫本地缓存:
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
- 开启日志!
- 测试在一个Session中查询两次相同记录
- 查看日志输出
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1o6zmrjI-1672735552224)(MyBatis.assets/image-20221213112553643.png)]
缓存失效的情况:
- 查询不同的东西;
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
- 查询不同的Mapper.xml
- 手动清理缓存;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7vxWxyXB-1672735552224)(MyBatis.assets/image-20221213112749610.png)]
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!一级缓存相当于一个Map, 更新后会重新查询取代原来的缓存。
9.4 二级缓存
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存(默认关闭, 需要手动开启). 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据就会放在自己对应的缓存(map)中;
步骤
1.在mybatis-config.xml开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>
3.可以自定义参数
<!--在当前Mapper.xml中使用二级缓存-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
测试.
若报错如下,我们需要将实体类序列化!(实现二级缓存时, Mybatis要求返回的pojo时可序列化的)
Cause: java.io.NotSerializableException: com.kuang.pojo.User
缓存回收策略
LRU
- 最近最少回收,移除最长时间不被使用的对象(默认)FIFO
- 先进先出,按照缓存进入的顺序来移除它们SOFT
- 软引用,移除基于垃圾回收器状态和软引用规则的对象WEAK
- 弱引用,更积极的移除基于垃圾收集器和弱引用规则的对象
小结
- 只要开启了二级缓存,在同一个Mapper下就有效;
- 所有的数据都会先放在一级缓存中;
- 只有当会话提交或者关闭的时候,才会提交到二级缓存中!
9.5 自定义缓存
Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存。
要在程序中使用ehcache,先要导包!
在mapper中指定使用我们的ehcache缓存实现!
目前:Redis数据库来做缓存!K-V
配置总结
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--外部配置文件-->
<properties resource="db.properties">
<!--这里可以增加一些属性,优先级低于 db.properties-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="pwd" value="12345"/>-->
</properties>
<settings>
<!--日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--开启驼峰命名自动映射. 如表中字段名user_name到属性名userName的映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<typeAlias type="com.lqz.pojo.Blog" alias="Blog"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--读取 db.properties 中配置-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册Mapper-->
<mappers>
<mapper class="com.lqz.dao.BlogMapper"/>
</mappers>
</configuration>
BlogMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lqz.dao.BlogMapper">
<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>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
</mapper>
工具类MybatisUtils.java
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用mybatis获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
//设置事务自动提交
return sqlSessionFactory.openSession(true);
}
}
测试使用
@Test
public void modifyBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
int count = mapper.modifyBlog("3", "mybatis", null);
if (count>0){
System.out.println("modify success");
}
sqlSession.close();
}
ironments>
BlogMapper.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lqz.dao.BlogMapper">
<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>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
</mapper>
工具类MybatisUtils.java
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用mybatis获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
//设置事务自动提交
return sqlSessionFactory.openSession(true);
}
}
测试使用
@Test
public void modifyBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
int count = mapper.modifyBlog("3", "mybatis", null);
if (count>0){
System.out.println("modify success");
}
sqlSession.close();
}