Mybatis
1.简述Mybatis
环境
- JDK1.8
- Mysql5.7
- maven3.6.1
- IDEA
回顾
- JDBC
- Mysql
- java基础
- Maven
- junit
SSM框架:配置文件的
1.1.什么是Mybatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
- 2013年11月迁移到Github。
2.第一个mybatis程序
2.1.搭建环境
搭建数据库
CREATE DATABASE mybatis;
USE `mybatis`;
CREATE TABLE `user` (
`id` INT ( 20 ) NOT NULL PRIMARY KEY,
`name` VARCHAR ( 20 ) DEFAULT NULL,
`pwd` VARCHAR ( 20 ) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=UTF8;
insert into `user` values
(1,'ts','123456'),
(2,'tang','456789'),
(3,'shuo','147288')
新建maven项目
-
新建一个普通的maven项目
-
删除src目录(把此项目当成一个父工程)
-
导入maven依赖
<?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.ts</groupId> <artifactId>Mybatis-study</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>mybatis-01</module> </modules> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <!----> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
2.2.创建一个模块
-
编写mybatis的核心配置文件(连接数据库)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration核心配置文件--> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="ts19990522"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/ts/dao/UserMapper.xml"/> </mappers> </configuration>
-
编写mybatis工具类
package com.ts.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{ 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 的实例。org.apache.ibatis.session.SqlSession //提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。 public static SqlSession getSqlSession(){ //SqlSessionFactory sqlSessionFactory = new SqlSessionFactory; //return sqlSessionFactory.openSession(); return sqlSessionFactory.openSession(); } }
2.3.编写代码
-
实体类
package com.ts.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 + '\'' + '}'; } }
-
Dao接口
package com.ts.dao;
import com.ts.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
- 接口实现类(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="com.ts.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="com.ts.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.4.测试
- junit
package com.ts.dao;
import com.ts.pojo.User;
import com.ts.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for(User user:userList){
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
}
2.5.遇到的问题
2.5.1.jdk与maven版本不匹配问题
解决办法:
1.打开File—>Project Structure
2.将下图的两个红框的版本改成相同的,我这里用的都是11
3.左方选择Model,将下图箭头所指的版本也改成11
4.将里面的所有模块的版本都改成11
5.以上的都修改完成后,退出来,选择File–>Settings
6.按照下图步骤进行修改,改成与之前所改的版本相同
遗留问题:这个办法确实可以解决问题,但是每次修改pom.xml里的代码,都必须重新配置一下。
2.5.2.绑定异常
错误原因:org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to theMapperRegistry.(绑定异常:类型接口Dao是未知的在Mapper注册中心),每一个Mapper.xml文件都需要在mybatis配置文件中注册!!!
注意:MapperRegistry是什么?
核心配置文件中注册mappers
解决办法:
在mybatis核心配置文件中加上Mapper.xml文件的注册
<mappers>
<mapper resource="com/ts/dao/UserMapper.xml"/>
</mappers>
注意:resource后面跟的是Mapper.xml的路径
2.5.3.配置文件无法导出问题(初始化问题)
Maven由于它的约定大于配置,我们可能会遇到我们所写的配置文件,无法被导出或者生效的问题,解决方案:手动在pom.xml配置过滤,代码如下:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
注意:最好主工程和子工程都放一份。
2.5.4.数据库时区问题
解决办法:在mybatis核心配置文件中加上UTC本地时区
3.CRUD(增删改查)
3.1.namespace
namespace中的包名要和Mapper接口中的包名一致!
3.2.select
- id:就是对应的namespace中的方法名
- resultType:sql语句执行的返回值
- parameterType:参数类型!
- 编写接口
package com.ts.dao;
import com.ts.pojo.User;
import java.util.List;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据id查用户
User getUserById(int id);
- 编写对应的mapper中的sql语句(实现接口)
<select id="getUserList" resultType="com.ts.pojo.User">
select * from user
</select>
<select id="getUserById" parameterType="int" resultType="com.ts.pojo.User">
select * from user where id = #{id}
</select>
- 测试
@Test
public void test(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for(User user:userList){
System.out.println(user);
}
//关闭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();
}
3.3.insert
<insert id="addUser" parameterType="com.ts.pojo.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
3.4.update
<update id="updateUserById" parameterType="com.ts.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
3.5.delete
<delete id="deleteUserById" parameterType="int">
delete from user where id = #{id}
</delete>
- 注意点:增删改需要提交事务!!!!
3.6.万能的Map
假设我们的实体类,或者数据库中的表,字段或者参数过多,我们应当使用Map!例如你遇到这种情况:User表中有id,name,pwd三个字段,现在要求将id=1的用户的name改为ts,这时,在UserMapper.xml文件中写实现时的参数只需要两个,id和user,但如果我们要根据实体类来取参,就会取到三个参数,这种情况,我们就可以用map。
1.使用map来添加一个用户
UserMapper接口:
int addUser2(Map<String, Object> map);
UserMapper.xml:
<insert id="addUser2" parameterType="map">
insert into user (id,name,pwd) values(#{userid},#{username},#{password})
</insert>
测试:
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userid",4);
map.put("username","sun");
map.put("password","334455");
int res = mapper.addUser2(map);
if(res > 0){
System.out.println("插入数据成功");
}
sqlSession.commit();
sqlSession.close();
}
2.使用map来双条件查询一个用户
UserMapper接口:
User getUserById2(Map<String,Object> map);
UserMapper.xml:
<select id="getUserById2" parameterType="map" resultType="com.ts.pojo.User">
select * from user where id = #{id} and name = #{name}
</select>
测试:
public void getUserById2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("name","wu");
User user = mapper.getUserById2(map);
System.out.println(user);
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可 parameterType=“map”
对象传递参数,直接在sql中取对象的属性即可 parameterType=“Object”
只有一个基本类型参数的情况下,可以直接在sql中取到!
3.7.模糊查询(两种方式)
1.在java代码执行的时候,传参时用% %
List<User> userList = mapper.getUserLike("%a%");
2.在sql中拼接时使用通配符% %
select * from user where name like "%"#{name}"%"
4.配置解析
4.1.核心配置文件
- mybatis-config.xml
- MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
注意:在xml中每一个标签都有固定的排序,如果不按规定进行排序,会报错!!!
4.2.环境配置(environments)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="..." value="..."/>
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
注意一些关键点:
- 默认使用的环境 ID(比如:default=“development”)。
- 每个 environment 元素定义的环境 ID(比如:id=“development”)。
- 事务管理器的配置(比如:type=“JDBC”)。
- 数据源的配置(比如:type=“POOLED”)。
事务管理器(transactionManager):在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]").
数据源(dataSource):dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
- 大多数 MyBatis 应用程序会按示例中的例子来配置数据源。虽然数据源配置是可选的,但如果要启用延迟加载特性,就必须配置数据源。
有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")
UNPOOLED :这个数据源的实现会每次请求时打开和关闭连接。虽然有点慢,但对那些数据库连接可用性要求不高的简单应用程序来说,是一个很好的选择
POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这种处理方式很流行,能使并发 Web 应用快速响应请求。
4.3.属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置
编写一个配置文件db.properties(放在resources目录下):
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=ts19990522
在核心配置文件中映入
<?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>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ts/dao/UserMapper.xml"/>
</mappers>
</configuration>
或者也可以这样写(增加一些属性配置):
<properties resource="db.properties">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
</properties>
如果一个属性在不只一个地方进行了配置,那么,MyBatis 将按照下面的顺序来加载:
- 首先读取在 properties 元素体内指定的属性。
- 然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。
- 最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。
因此,通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的则是 properties 元素中指定的属性。
4.4.类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字
- 意在降低冗余的全限定类名书写
第一种方法:自定义别名
<typeAliases>
<typeAlias type="com.ts.pojo.User" alias="user"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
扫面实体类的包,它的默认别名就为这个类的类名,类名首字母大小写都可以,建议用小写
<typeAliases>
<package name="com.ts.pojo"/>
</typeAliases>
第一种可以自定义别名,第二种则“不行”,如果非要改,需要在实体类上加注解
@Alias("hello")
public class User {}
4.5.设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7VTjbQ1f-1636108393771)(D:\MarkdownPicture\image-20211029163500993.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0m4ybqb0-1636108393772)(D:\MarkdownPicture\image-20211029163518105.png)]
4.6.其他配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
4.7.映射器(mappers)
MapperRegistry:注册绑定我们的mappers
方法一(推荐使用):通过xml文件找
<mappers>
<mapper resource="com/ts/dao/UserMapper.xml"/>
</mappers>
方式二:通过class文件绑定注册
<mappers>
<mapper class="com.ts.dao.UserMapper"/>
</mappers>
注意点:
- 接口和他的配置文件必须同名
- 接口和他的配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.ts.dao"/>
</mappers>
注意点(与方式二一样):
- 接口和他的配置文件必须同名
- 接口和他的配置文件必须在同一个包下
4.8.生命周期和作用域
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder
- 一旦创建了SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory
- 可以想象为数据口连接池
- SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 因此SqlSessionFactory的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession
- 连接到连接池的一个请求
- SqlSession的实例不是线程安全的,因此不能被共享的,所以它的最佳作用域是请求或方法作用域
- 用完之后需要赶紧关闭,否则资源被占用!
这里的每一个Mapper,就代表一个具体的业务
5.解决属性名和字段不一致的问题
5.1.问题
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
private int id;
private String name;
private String password;
测试出现了问题
解决方法
- 起别名
<select id="getUserByName" resultType="com.ts.pojo.User">
select id,name,pwd as password from user where name = #{name}
</select>
5.2.resultMap解决
<mapper namespace="com.ts.dao.UserMapper">
<resultMap id="map" type="com.ts.pojo.User">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="password" column="pwd"/>
</resultMap>
<select id="getUserByName" resultMap="map">
select id,name,pwd from user where name = #{name}
</select>
</mapper>
resultMap
元素是 MyBatis 中最重要最强大的元素- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
ResultMap
的优秀之处——你完全可以不用显式地配置它们- 如果世界总是这么简单就好了…
6.日志
6.1.日志工厂
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout,debug
现在:日志工厂!
- SLF4J
- LOG4J
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
在Mybatis中具体使用哪一个日志实现,在核心配置文件中设置设定
STDOUT_LOGGING 标准日志输出
配置:
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
运行结果:
6.2.什么是Log4j
什么是Log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
1.先导入log4j的包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/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>
4.使用Log4j,测试
6.3.简单使用
1.在要使用log4j的类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前的class
static Logger logger = Logger.getLogger(UserMappperTest.class);
3.日志级别
logger.info("info:进入了TestLog4j");
logger.debug("debug:进入了TestLog4j");
logger.error("error:进入了TestLog4j");
7.分页
7.1为什么要使用分页
- 减少数据的处理量
使用Limit分页
语法:select * from user limit startIndex,pageSize
举例:
select * from user limit 0,4/*从第一个数据查到第四个数据*/
使用Mybatis实现分页,核心就是sql
- 接口
public List<User> getUserByLimit(Map<String,Object> map)2;
- Mapper.xml
<select id="getUserByLimit" resultType="com.ts.pojo.User">
select * from user limit #{startIndex},#{pageSize}
</select>
- 测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("startIndex",0);
map.put("pageSize",4);
List<User> userList = mapper.getUserByLimit(map);
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
7.2.RowBounds分页
- 接口
//分页2
public List<User> getUserByRowBounds();
- mapper.xml
=<select id="getUserByRowBounds" resultMap="map">
select * from user;
</select>
- 测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
RowBounds rowBounds = new RowBounds(1,2);
//通过java代码层面实现分页
List<User> userList = sqlSession.selectList("com.ts.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.3.分页插件
8.使用注解开发
8.1.使用注解开发
1.注解在接口上实现
//查询全部用户
@Select("select * from user")
List<User> getUserList();
2.需要在核心配置文件中绑定
<mappers>
<mapper class="com.ts.dao.UserMapper"/>
</mappers>
3.测试
@Test
public void test(){
//1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//2.getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
本质:反射机制实现
底层:动态代理!
8.2.CRUD
我们可以在工具类创建的时候实现自动提交事物
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
@Select("select * from user where id = #{id}")
List<User> getUserById(@Param("id") int id);
@Insert("insert into user values(#{id},#{name},#{pwd})")
int addUser(@Param("id") int id ,@Param("name") String name ,@Param("pwd") String pwd);
@Update("update user set name = #{name} where id = #{id}")
int updateUsernameById(@Param("id") int id ,@Param("name") String name);
@Delete("delete from user where id = #{id}")
int deleteUserById(@Param("id") int id);
测试
【注意:我们必须要将接口注册绑定到我们的核心配置文件中!】
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserById(1);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.addUser(6,"zs","12233");
sqlSession.close();
}
@Test
public void updateUsernameById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.updateUsernameById(1,"ts");
sqlSession.close();
}
@Test
public void deleteUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteUserById(6);
sqlSession.close();
}
8.3. 关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议加上
- 我们在sql中引用的就是我们这里的@Param()中设定的属性名
8.4. 关于#{}与${}的区别
9.Mybatis执行过程
10.Lombok
Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。
使用步骤:
1.在idea中安装Lombok插件
2.在项目中导入Lombok的包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
说明:
@Data:无参构造,get,set,tostring,hashcode,equals
@AllArgsConstructor:有参构造
@NoArgsConstructor:无参构造
@EqualsAndHashCode:hashcode,equals
@ToString
@Getter and @Setter
11.多对一处理
- 多个学生,对应一个老师
- 对于学生而言,关联,多个学生,关联一个老师【多对一】
- 对于老师而言,集合,一个老师,有很多学生【一对多】
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);
11.1.测试环境搭建
- 导入lombok
- 新建实体类Teacher,Student
//学生实体类
package com.ts.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
//老师实体类
package com.ts.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件!
- 测试查询是否成功
11.2.按照查询嵌套查询
类似子查询
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ts.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="Student" >
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
</resultMap>
<select id="getTeacherById" resultType="Teacher">
select * from teacher where id = #{id};
</select>
</mapper>
11.3.按照结果嵌套处理
类似连表查询
<select id="getStudent2" resultMap="StudentTeacher2">
select student.id sid,student.name sname,teacher.name tname
from student,teacher
where student.tid = teacher.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
12.一对多处理
12.1.按照查询嵌套查询
<select id="getTeacherById2" resultMap="TeacherStudent2">
select * from teacher where id = #{id};
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="id"/>
<collection property="student" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid};
</select>
12.2.按照结果嵌套查询
<select id="getTeacherById" resultMap="TeacherStudent">
select teacher.id tid , teacher.name tname , student.id sid , student.name sname
from student,teacher
where student.tid = teacher.id and teacher.id = #{id};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="student" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
12.3.小结
- 关联:association【多对一使用】
- 集合:collection【一对多使用】
- javaType和ofType
- javaType用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型的约束类型!
注意点:
- 保证SQL的可读性
- 注意一对多和多对一,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用log4j
13.动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
13.1.搭建环境
数据库:
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;
创建一个maven项目:
- 导包
- 编写配置文件
- 编写实体类
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
开启驼峰命名映射数据库命名
- 编写工具类
- 编写实体类对应的Mapper接口和Mapper.xml文件
13.2.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>
13.3.choose (when, otherwise)
相当于java中的case语句
<select id="getBlogWhen" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
<otherwise>
views = #{views}
</otherwise>
</choose>
</where>
</select>
13.4.trim (where, set)
<select id="getBlogIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
<update id="updateBlog" parameterType="map" >
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
<where>
id = #{id}
</where>
</update>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面执行一个逻辑代码
13.5.SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用
1.使用SQL标签抽取公共的部分
<sql id="if">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
2.在需要使用的地方使用include标签引用即可
<select id="getBlogIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if"/>
</where>
</select>
注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where标签
13.6.Foreach
实现
select * from blog where (id = 1 or id = 2 or id = 3)
接口:
List<Blog> getBlogForeach(Map map);
实现类:
<select id="getBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
注意:
- collection:集合(map对象可以存放一个集合)
- item:集合中的每个元素
- open:拼接的开头
- separator:分隔符
- close:拼接的尾部
测试:
@Test
public void getBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<String> ids = new ArrayList<>();
ids.add("1c0f4415a6d44584b8dd7a1b20a987a3");
ids.add("89aa2a304e5c445bb5e2dd5b03b432f5");
ids.add("25f3fe1b875d4e1aa58d8409443c52f3");
//ids.add("d7e01e22024b4f09b9dce9234e48c3a3");
map.put("ids",ids);
List<Blog> blogList = mapper.getBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式去排列组合就可以了!
14.缓存
14.1.简介
查询数据库耗费资源!我们可以将一个查询的结果给他暂时存在一个地方——>内存:缓存。当我们再次查询相同的数据的时候,我们就可以直接走缓存,不用走数据库了。
- 什么是缓存(Cache)?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么样的数据能使用换存
- 经常查询并且不经常改变的数据
14.2.Mybatis缓存
- Mybatis包含一个非常强大的缓存特性,它可以非常方便的配置缓存,缓存可以极大的提升查询效率
- Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启,(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
- 为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
14.3.一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果类要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试:按id查询用户,在一个SqlSession中进行两次相同的查询
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUserById(1);
System.out.println(user1);
System.out.println("======================================");
User user2 = mapper.getUserById(1);
System.out.println(user2);
sqlSession.close();
运行结果:只进行了一次查询!
缓存失效的情况:
-
查询不同的东西
-
增删改操作,可能会改变原来的数据,所以必定会刷新缓存
接口:
public interface UserMapper {
User getUserById(@Param("id") int id);
int updateUser(User user);
}
实现:
<mapper namespace="com.ts.dao.UserMapper">
<select id="getUserById" resultType="User" parameterType="int">
select * from User where id = #{id}
</select>
<update id="updateUser" parameterType="User">
update user set name = #{name} , pwd = #{pwd} where id = #{id}
</update>
</mapper>
测试:我们在两条相同的查询语句之间加一个update语句
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUserById(1);
System.out.println(user1);
System.out.println("======================================");
mapper.updateUser(new User(1,"aaaaa","bbbbbb"));
User user2 = mapper.getUserById(1);
System.out.println(user2);
sqlSession.close();
}
运行结果:
可以看到,我们更改的2号用户,但两次查询都是3号用户,Mybatis还是进行了两此查询!
- 查询不同的Mapper.xml
- 手动清理缓存
测试:
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUserById(3);
System.out.println(user1);
sqlSession.clearCache();//清理缓存
System.out.println("======================================");
User user2 = mapper.getUserById(3);
System.out.println(user2);
sqlSession.close();
}
运行结果:两次相同的查询进行了两次!
小结:一级缓存是默认开启的,只有在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!一级缓存就是一个Map
14.4.二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个命名空间,对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了,但我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤:
- 开启全局缓存
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
- 在要使用二级缓存的Mapper中开启
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
可用的清除策略有:
LRU
– 最近最少使用:移除最长时间不被使用的对象。FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
默认的清除策略是 LRU。
测试:
- 问题:我们需要将实体类序列化!否则就会报错
Caused by: java.io.NotSerializableException: com.ts.pojo.User
解决:在User实体类实现接口Serializable
public class User implements Serializable {}
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会事先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存。
14.5.缓存原理
14.6.自定义缓存-ehcache
ehcache是一种广泛使用的开源java分布式缓存,主要面向通用缓存。
要在程序中和使用ehcache,先要导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.EhcacheCache"/>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<!--
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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>