MyBatis
简介
什么是 MyBatis?
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
如何获得MyBatis?
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
- Github:https://github.com/mybatis/mybatis-3
- 中文文档:https://mybatis.org/mybatis-3/zh/index.html
持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬间状态转化的过程
- 内存:断电即失
- 数据库(JDBC):io文件持久化
持久层
Dao层,Service层,Controller层…
MyBatis特点
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离。sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
第一个MyBatis程序
1、搭建环境
搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`)
VALUES(1,'刚龙','123456'),(2,'倩倩','123456'),(3,'肖总','123456')
新建项目
- 新建一个普通的maven项目
- 删除src目录
- 导入maven依赖
pom.xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
2、创建一个模块
- 编写mybatis的核心配置文件
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=ture&characterEncoding=UTF-8" />
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
- 编写mybatis工具类
package com.sgl.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 {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3、编写代码
- 实体类
package com.sgl.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.sgl.dao;
import com.sgl.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
- 接口实现类 由原来的UserDaoImpl转换为Mapper配置文件
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.UserDao">
<select id="getUserList" resultType="com.sgl.pojo.User">
select * from mybatis.user
</select>
</mapper>
3、测试
MapperRegistry是什么?
核心配置文件注册mappers
package com.sgl.dao;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
}
}
}
结果:
CRUD
1、namespace
namespace中的包名要和Dao/mapper接口的包名一致
2、select
选择、查询语句:
- id:对应的UserMapper接口中的方法名;
- resultType:Sql语句执行的返回值
- parameterType:参数类型
- 编写接口
UserMapper
package com.sgl.dao;
import com.sgl.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
- 编写对应的mapper语句
UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.UserMapper">
<select id="getUserList" resultType="com.sgl.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" resultType="com.sgl.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.sgl.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.sgl.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id} ;
</update>
<delete id="deleteUser" parameterType="com.sgl.pojo.User" >
delete from mybatis.user where id=#{id};
</delete>
</mapper>
- 测试
package com.sgl.dao;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
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 res = mapper.addUser(new User(5, "憨老表", "155555"));
if (res>0){
System.out.println("插入成功!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(5,"憨货","555555"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(5);
sqlSession.commit();
sqlSession.close();
}
}
增删改需要提交事务
3、insert
代码在上面
4、update
代码在上面
5、delete
代码在上面
6、Map(了解)
假设,我们的实体类,或者数据库中的表,字段过多,我们应当使用Map
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,pwd) values (#{userId},#{userPwd});
</insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("userId",5);
map.put("userPwd","666666");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可 [parameterType=“map”]
对象传递参数,直接在sql中取对象的属性即可 [parameterType=“Object”]
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解
配置解析
1、核心配置文件
- mybatis-config.xml
- MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
configuration(配置) ********
properties(属性) ********
settings(设置) ********
typeAliases(类型别名) ********
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置) ********
environment(环境变量) ********
transactionManager(事务管理器) ********
dataSource(数据源) ********
databaseIdProvider(数据库厂商标识)
mappers(映射器) ********
2、环境配置(environments)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
- JDBC – 这个配置直接使用JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
- MANAGED – 这个配置几乎没做什么
数据源(dataSource)
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
- 大多数 MyBatis 应用程序会按示例中的例子来配置数据源。虽然数据源配置是可选的,但如果要启用延迟加载特性,就必须配置数据源。
有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):
UNPOOLED POOLED JNDI
3、属性(properties)
可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置 db.properties
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
在核心配置文件(mybatis-config.xml)中引入
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
- 可以直接引入外部配置文件
- 可以在其中加入一些属性配置
- 如果有两个文件有同一个字段,优先使用外部配置文件
4、类型别名(typeAliases)
- 类型别名是为Java类型设置一个短的名字,用于减少类完全限定名的
<typeAliases>
<typeAlias type="com.sgl.pojo.User" alias="User"/>
</typeAliases>
- 也可以指定一个包名,MyBatis会在包名下面搜索需要的javaBean,比如:
扫描实体类的包,他的默认别名就为这个类的 类名,首字母小写
<typeAliases>
<package name="com.sgl.pojo"/>
</typeAliases>
实体类比较少,建议使用第一种方式(可以DIY(自定义)别名)
实体类较多,建议使用第二种方式(不可DIY(自定义)别名,如果非要改,需要在实体类上增加注解如下:
@Alias("user")
public class User {}
5、设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
设置名 | 描述 | 有效值 | 默认值 |
---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true | lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 | true | false | false | logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J 、LOG4J 、 LOG4J2 、 JDK_LOGGING 、 COMMONS_LOGGING 、 STDOUT_LOGGING 、 NO_LOGGING | 未设置 |
6、映射器(mapper)
MapperRegistry:注册绑定我们的Mapper文件
方式一:
<mappers>
<mapper resource="com/sgl/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.sgl.dao.UserMapper"/>-->
</mappers>
方式三:使用扫描包进行注册绑定
<mappers>
<package name="com.sgl.dao"/>-->
</mappers>
方式二和方式三注意点:
- 接口和他的Mapper配置文件必须同名
- 接口和他的配置文件必须在同一个包下
7、其他配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
作用域(Scope)和生命周期
SqlSessionFactoryBuilder
- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 因此 SqlSessionFactory 的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession
- 连接到连接池的一个请求
- 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
- 用完之后需要关闭,否则资源被占用
解决属性名和字段名不一致的问题
数据库的字段和实体类的属性名
测试查询结果:
出现问题
解决方法:
<select id="getUserById" resultType="com.sgl.pojo.User" parameterType="int">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
resultMap(结果映射)
结果集映射
id name pwd
id name password
<resultMap id="UserMap" type="com.sgl.pojo.User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
resultMap 元素是 MyBatis 中最重要最强大的元素- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
ResultMap 的优秀之处——你完全可以不用显式地配置它们(就是相同的字段可以省略)
<resultMap id="UserMap" type="com.sgl.pojo.User">
<result column="pwd" property="password"/>
</resultMap>
解决后的结果:
日志
日志工厂
设置名 | 描述 | 有效值 | 默认值 |
---|
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找 | SLF4J 、LOG4J 、 LOG4J2 、 JDK_LOGGING 、 COMMONS_LOGGING 、 STDOUT_LOGGING 、 NO_LOGGING | 未设置 |
在mybatis核心配置文件中,配置我们的日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
输出的结果:
LOG4J
什么是log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
- 先导入log4j包(maven仓库查找)
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- 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/sgl.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
- 配置log4j日志的实现(核心文件mybatis-config.xml中配置)
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
输出的结果: LOG4J与STDOUT_LOGGING输出结果基本一样
简单使用
- 在要使用Log4j的类中,导入包import org.apache.log4j.Logger;
- 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 日记级别
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
分页
Limit分页
MySQL使用Limit分页
语法:
SELECT * FROM user LIMIT startIndex,pageSize;
SELECT * FROM user LIMIT 3;
使用Mybatis实现分页,核心SQL
- 接口UserMapper.java
List<User> getUserByLimit(Map<String,Integer> map);
- UserMapper.xml
<resultMap id="UserMap" type="com.sgl.pojo.User">
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserByLimit" resultMap="UserMap" parameterType="map">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
- 测试UserDaoTest
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
- 测试结果
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 1337344609.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4fb64261]
[com.sgl.dao.UserMapper.getUserByLimit]-==> Preparing: select * from mybatis.user limit ?,?
[com.sgl.dao.UserMapper.getUserByLimit]-==> Parameters: 0(Integer), 2(Integer)
[com.sgl.dao.UserMapper.getUserByLimit]-<== Total: 2
User{id=1, name='刚龙', password='123456'}
User{id=2, name='倩倩', password='123456'}
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4fb64261]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4fb64261]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 1337344609 to pool.
Process finished with exit code 0
RowBounds分页
- 接口UserMapper.java
List<User> getUserByRowBounds();
- UserMapper.xml
<resultMap id="UserMap" type="com.sgl.pojo.User">
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
- 测试UserDaoTest
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(0, 2);
List<User> userList = sqlSession.selectList("com.sgl.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
- 测试结果
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 911312317.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@365185bd]
[com.sgl.dao.UserMapper.getUserByRowBounds]-==> Preparing: select * from mybatis.user
[com.sgl.dao.UserMapper.getUserByRowBounds]-==> Parameters:
User{id=1, name='刚龙', password='123456'}
User{id=2, name='倩倩', password='123456'}
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@365185bd]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@365185bd]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 911312317 to pool.
Process finished with exit code 0
分页插件(了解)
链接:https://pagehelper.github.io/
使用注解开发
注解增删改查(CRUD)
- 注解在接口上实现 UserMapper接口
@Select("select * from user")
List<User> getUsers();
- 核心配置文件中绑定接口 mybatis-config.xml
<mappers>
<mapper class="com.sgl.dao.UserMapper"/>
</mappers>
- 测试
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUsers();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
CRUD
- 在工具类(MybatisUtils)创建的时候实现自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
- 核心配置文件中绑定接口 mybatis-config.xml
<mappers>
<mapper class="com.sgl.dao.UserMapper"/>
</mappers>
- 编写接口 增加注解
package com.sgl.dao;
import com.sgl.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
@Select("select * from user where id =#{id}")
User getUserByID(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id=#{uid}")
int deleteUser(@Param("uid") int id);
}
- 测试类 UserMapperTest
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUsers();
for (User user : userList) {
System.out.println(user);
}
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);
mapper.addUser(new User(6,"周总","88888"));
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(6,"狗哥","698574"));
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(6);
sqlSession.close();
}
}
@Param注解
- 基本类型的参数或者String类型的参数,需要加上
- 引用类型不需要加上
- 如果只有一个基本类型,可加可不加(建议加上)
- 在SQL中引用的就是@Param中设定的属性名
本质:反射机制实现 底层:动态代理(婚庆公司案例)
Mybatis执行流程
Lombok(了解)
ProjectLombok是一个java库,可以自动插入编辑器和构建工具,提高java的性能。永远不要再编写另一个getter或equals方法,使用一个注释,您的类就有了一个功能齐全的生成器,自动化了您的日志变量
使用步骤:
- 在IDEA中安装Lombok插件(有就不用安装)
- 在项目中导入Lombok的jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</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,hashCode,canEqual
@AllArgsConstructor: 有参
@NoArgsConstructor: 无参
@EqualsAndHashCode : equals,hashCode,canEqual
效果:
多对一处理
多个学生对应一个老师
测试环境搭建(回顾之间知识)
SQL语句:
USE mybatis;
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
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')
- 导入Lombok-------->Lombok(了解)
- 新建实体类Teacher,Student
package com.sgl.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private Teacher teacher;
}
package com.sgl.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
- 建立Mapper接口 StudentMapper TeacherMapper
package com.sgl.dao;
public interface StudentMapper {
}
package com.sgl.dao;
import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id =#{tid}")
Teacher getTeacher(@Param("tid") int id);
}
- 建立Mapper.xml文件 StudnetMapper.xml TeacherMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.StudentMapper">
</mapper>
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.TeacherMapper">
</mapper>
- 在核心配置文件(mybatis-config.xml)中绑定注册我们的Mapper接口或文件
<mappers>
<mapper class="com.sgl.dao.TeacherMapper"/>
<mapper class="com.sgl.dao.StudentMapper"/>
</mappers>
- 测试查询是否成功
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
按照查询嵌套处理
StudentMapper 和 TeacherMapper 接口
package com.sgl.dao;
import com.sgl.pojo.Student;
import java.util.List;
public interface StudentMapper {
public List<Student> getStudent();
}
package com.sgl.dao;
import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id =#{tid}")
Teacher getTeacher(@Param("tid") int id);
}
StudentMapper.xml
<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="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
按照结果嵌套处理
StudentMapper 和 TeacherMapper 接口
package com.sgl.dao;
import com.sgl.pojo.Student;
import java.util.List;
public interface StudentMapper {
public List<Student> getStudent2();
}
package com.sgl.dao;
import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id =#{tid}")
Teacher getTeacher(@Param("tid") int id);
}
StudentMapper.xml
<select id="getStudent2" resultMap="StudentTeacher2">
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="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
测试
import com.sgl.dao.StudentMapper;
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Student;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
@Test
public void getStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudent();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
@Test
public void getStudent2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudent2();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
}
按照查询嵌套处理:
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1540270363.
==> Preparing: select * from student
==> Parameters:
<== Columns: id, name, tid
<== Row: 1, 小明, 1
====> Preparing: select * from teacher where id = ?
====> Parameters: 1(Integer)
<==== Columns: id, name
<==== Row: 1, 秦老师
<==== Total: 1
<== Row: 2, 小红, 1
<== Row: 3, 小张, 1
<== Row: 4, 小李, 1
<== Row: 5, 小王, 1
<== Total: 5
Student(id=1, name=小明, teacher=Teacher(id=1, name=秦老师))
Student(id=2, name=小红, teacher=Teacher(id=1, name=秦老师))
Student(id=3, name=小张, teacher=Teacher(id=1, name=秦老师))
Student(id=4, name=小李, teacher=Teacher(id=1, name=秦老师))
Student(id=5, name=小王, teacher=Teacher(id=1, name=秦老师))
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5bcea91b]
Returned connection 1540270363 to pool.
按照结果嵌套处理:
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1540270363.
==> Preparing: select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id
==> Parameters:
<== Columns: sid, sname, tid, tname
<== Row: 1, 小明, 1, 秦老师
<== Row: 2, 小红, 1, 秦老师
<== Row: 3, 小张, 1, 秦老师
<== Row: 4, 小李, 1, 秦老师
<== Row: 5, 小王, 1, 秦老师
<== Total: 5
Student(id=1, name=小明, teacher=Teacher(id=1, name=秦老师))
Student(id=2, name=小红, teacher=Teacher(id=1, name=秦老师))
Student(id=3, name=小张, teacher=Teacher(id=1, name=秦老师))
Student(id=4, name=小李, teacher=Teacher(id=1, name=秦老师))
Student(id=5, name=小王, teacher=Teacher(id=1, name=秦老师))
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5bcea91b]
Returned connection 1540270363 to pool.
一对多处理
一个老师对应多个学生
测试环境搭建
- 导入Lombok-------->Lombok(了解)
- 新建实体类Teacher,Student
package com.sgl.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
package com.sgl.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
- 建立Mapper接口 StudentMapper TeacherMapper
package com.sgl.dao;
public interface StudentMapper {
}
package com.sgl.dao;
import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface TeacherMapper {
List<Teacher> getTeacher();
}
- 建立Mapper.xml文件 StudnetMapper.xml TeacherMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.StudentMapper">
</mapper>
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.TeacherMapper">
<select id="getTeacher" resultType="Teacher">
select * from teacher
</select>
</mapper>
- 在核心配置文件(mybatis-config.xml)中绑定注册我们的Mapper接口或文件
<mappers>
<mapper class="com.sgl.dao.TeacherMapper"/>
<mapper class="com.sgl.dao.StudentMapper"/>
</mappers>
- 测试查询是否成功
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List<Teacher> teacherList = mapper.getTeacher();
for (Teacher teacher : teacherList) {
System.out.println(teacher);
}
sqlSession.close();
}
}
按照查询嵌套处理
TeacherMapper.xml
<select id="getTeacher2" resultMap="TeacherStudent2">
select id,name from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
</resultMap>
<select id="getStudent" resultType="Student">
select id,name,tid from mybatis.student where tid=#{tid}
</select>
按照结果嵌套处理
StudentMapper 和 TeacherMapper 接口
package com.sgl.dao;
public interface StudentMapper {
}
package com.sgl.dao;
import com.sgl.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface TeacherMapper {
List<Teacher> getTeacher();
Teacher getTeacher1(@Param("tid") int id);
Teacher getTeacher2(@Param("tid") int id);
}
TeacherMapper.xml
<select id="getTeacher1" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname
from teacher t,student s
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="tname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
测试
import com.sgl.dao.TeacherMapper;
import com.sgl.pojo.Teacher;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List<Teacher> teacherList = mapper.getTeacher();
for (Teacher teacher : teacherList) {
System.out.println(teacher);
}
sqlSession.close();
}
@Test
public void getTeacher(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher1(1);
System.out.println(teacher);
sqlSession.close();
}
@Test
public void getTeacher2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher2(1);
System.out.println(teacher);
sqlSession.close();
}
}
按照查询嵌套处理:
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 648525677.
==> Preparing: select id,name from mybatis.teacher where id=?
==> Parameters: 1(Integer)
<== Columns: id, name
<== Row: 1, 秦老师
====> Preparing: select id,name,tid from mybatis.student where tid=?
====> Parameters: 1(Integer)
<==== Columns: id, name, tid
<==== Row: 1, 小明, 1
<==== Row: 2, 小红, 1
<==== Row: 3, 小张, 1
<==== Row: 4, 小李, 1
<==== Row: 5, 小王, 1
<==== Total: 5
<== Total: 1
Teacher(id=1, name=秦老师, students=[Student(id=1, name=小明, tid=1), Student(id=2, name=小红, tid=1), Student(id=3, name=小张, tid=1), Student(id=4, name=小李, tid=1), Student(id=5, name=小王, tid=1)])
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@26a7b76d]
Returned connection 648525677 to pool.
按照结果嵌套处理:
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 648525677.
==> Preparing: select t.id tid,t.name tname,s.id sid,s.name sname from teacher t,student s where s.tid=t.id and t.id=?
==> Parameters: 1(Integer)
<== Columns: tid, tname, sid, sname
<== Row: 1, 秦老师, 1, 小明
<== Row: 1, 秦老师, 2, 小红
<== Row: 1, 秦老师, 3, 小张
<== Row: 1, 秦老师, 4, 小李
<== Row: 1, 秦老师, 5, 小王
<== Total: 5
Teacher(id=1, name=秦老师, students=[Student(id=1, name=秦老师, tid=1), Student(id=2, name=秦老师, tid=1), Student(id=3, name=秦老师, tid=1), Student(id=4, name=秦老师, tid=1), Student(id=5, name=秦老师, tid=1)])
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@26a7b76d]
Returned connection 648525677 to pool.
一对多,多对一小结和注意点
小结:
- 关联 association (多对一)
- 集合 collection (一对多)
- JavaType 和 ofType
- JavaType用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一中属性和字段的问题
- 问题不好排查,查看前方笔记,使用日志,建议使用Log4j
面试高频
MySQL引擎、INNODB底层原理、索引、索引优化(查文章看一下)
动态SQL
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
环境搭建
SQL语句:
CREATE TABLE `blog` (
`id` VARCHAR(30) NOT NULL COMMENT '博客id',
`title` VARCHAR(30) 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
创建一个基础工程
- 导包(偷懒用的)
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
- 编写核心配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.sgl.pojo"/>
</typeAliases>
<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 class="com.sgl.dao.BlogMapper"/>
</mappers>
</configuration>
- 编写实体类
package com.sgl.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
- 编写实体类对应的Mapper接口
package com.sgl.dao;
import com.sgl.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
int addBook(Blog blog);
}
- 编写Mapper.xml文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.BlogMapper">
<insert id="addBook" parameterType="Blog">
insert into mybatis.blog (id,title,author,create_time,views)
values(#{id},#{title},#{author},#{createTime},#{views})
</insert>
</mapper>
测试并插入数据:
- 编写一个自动生成ID的工具类 IDutils.java
package com.sgl.utils;
import org.junit.Test;
import java.util.UUID;
@SuppressWarnings("all")
public class IDutils {
public static String getID(){
return UUID.randomUUID().toString().replace("-","");
}
@Test
public void test(){
System.out.println(IDutils.getID());
}
}
- 插入数据
import com.sgl.dao.BlogMapper;
import com.sgl.pojo.Blog;
import com.sgl.utils.IDutils;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void addBook(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(9999);
blog.setId(IDutils.getID());
blog.setTitle("Mybatis");
mapper.addBook(blog);
blog.setId(IDutils.getID());
blog.setTitle("Java");
mapper.addBook(blog);
blog.setId(IDutils.getID());
blog.setTitle("Spring");
mapper.addBook(blog);
blog.setId(IDutils.getID());
blog.setTitle("微服务");
mapper.addBook(blog);
sqlSession.close();
}
}
IF
BlogMapper接口
package com.sgl.dao;
import com.sgl.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
int addBook(Blog blog);
List<Blog> queryBlogIf(Map map);
}
BlogMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.BlogMapper">
<insert id="addBook" parameterType="Blog">
insert into mybatis.blog (id,title,author,create_time,views)
values(#{id},#{title},#{author},#{createTime},#{views})
</insert>
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
</mapper>
测试:
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
choose(when,otherwise)
<select id="queryBlogChoose" resultType="blog" parameterType="map">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
trim(where,set)
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
where和set的作用
所谓动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
SQL片段
有时候可能会将一些功能抽取出来,方便重复使用
- 使用SQL标签抽取公共的部分
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
- 在需要使用的地方使用include标签引用即可
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"/>
</where>
</select>
注意事项:
- 最好基于单表来定义SQL片段
- SQL标签不要存在where标签,否则实现不了重复使用
Foreach
foreach(官方文档)
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符
案例
SQL
插入代码重新运行以下插入数据,并修改了id为1,2,3,4,修改后要提交事务
BlogMapper接口
List<Blog> queryBlogForEach(Map map);
BlogMapper.xml
<select id="queryBlogForEach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
测试:
@Test
public void queryBlogForEach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(4);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForEach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
结果:
动态SQL就是在拼接SQL语句,要保证SQL的正确性,按照SQL的格式
缓存
简介
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据不用在从磁盘上查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
作用:减少和数据库的交互次数,减少系统的开销,提高系统效率
Mybatis缓存
- Mybatis包含一个非常强大的查询缓存特性,可以非常方便地定制和配置缓存,缓存可以极大地提升查询效率
- Mybatis系统默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别地缓存,也称本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别地缓存
- 为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
?
一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到地数据会放在本地缓存中
- 以后需要获取相同地数据,直接从缓存中取数据,不必再去查询数据库
一级缓存是默认开启的,只在一次SqlSession中有效(连接到关闭之间的区间有效)
测试:
UserMapper接口
package com.sgl.dao;
import com.sgl.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
User queryUserById(@Param("id") int id);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sgl.dao.UserMapper">
<select id="queryUserById" resultType="user">
select * from mybatis.user where id=#{id}
</select>
</mapper>
测试:
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void queryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
sqlSession.clearCache();
System.out.println(user);
System.out.println("=========================");
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
结果:
清理掉缓存之后的结果: sqlSession.clearCache();
缓存失效的情况
- 查询不同的东西
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void queryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
System.out.println("=========================");
User user2 = mapper.queryUserById(2);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
}
效果:
- 增删改操作,可能会改变原来的数据,所以必定会刷新
? 在两次查询之间,插入修改语句
package com.sgl.dao;
import com.sgl.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
User queryUserById(@Param("id") int id);
int updateUser(User user);
}
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void queryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
System.out.println("=========================");
User user2 = mapper.queryUserById(2);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
}
效果:
- 查询不同的Mapper.xml文件
- 手动清理缓存
sqlSession.clearCache();
二级缓存
- 二级缓存也叫全局缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制:
- 一个会话查询一条数据,这个数据会被放在当前会话的一级缓存中
- 如果会话关闭了,这个会话对应的一级缓存就没了;但是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤:
- 开启全局缓存
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
- 在要使用二级缓存的Mapper中开启
方式一:
<cache/>
方式二:
也可以自定义参数
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
- 测试
UserMapper.xml 加入参数**useCache=“true”**使用缓存
<select id="queryUserById" resultType="user" useCache="true">
select * from mybatis.user where id=#{id}
</select>
MyTest.java(两个SqlSession,所以最后为false)
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void queryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
sqlSession.close();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession2.close();
}
}
使用方式一开启缓存,测试MyTest.java会报错 ----> 解决:需要将实体类序列化
Caused by: java.io.NotSerializableException: com.sgl.pojo.User
继承Serializable接口
public class User implements Serializable {}
结果:
MyTest.java (一个SqlSession,所以为true)
import com.sgl.dao.UserMapper;
import com.sgl.pojo.User;
import com.sgl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void queryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
}
结果:
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
Mybatis缓存原理
自定义缓存-ehcache
Eahcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
- 在程序中使用ehcache,先导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
- 在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
- ehcache.xml(在resource资源目录下)
<?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 path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
完结
|