MyBatis
目录
1. 简介
1.1 什么是 MyBatis
- 持久层框架
- 支持定制化
SQL
、存储过程以及高级映射 MyBatis
避免了几乎所有的JDBC
代码和手动设置参数以及获取结果集。MyBatis
可以使用简单的XML
或注解来配置和映射原生类型、接口和Java
的POJO(Plain Old Java Objects,普通老式Java对象)
为数据库中的记录。
1.2 如何获取 Mybatis
-
Maven
仓库:https://mvnrepository.com/search?q=mybatis<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> // 静态资源过滤 <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>
-
GitHub
-
中文文档:https://mybatis.org/mybatis-3/zh/index.html
1.3 持久化
-
数据持久化
- 持久化就是指将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(JDBC)、IO文件持久化
1.4 持久层
Dao层、Service层、Controller层…
- 完成持久化工作的代码块
- 层界限十分明显
1.5 MyBatis 重要性
- 便利,传统的JDBC代码过于复杂,用以简化框架,自动化
- 解除
sql
与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql
和代码的分离,提高了可维护性 - 提供映射标签,支持对象与数据库的
orm
字段关系映射 - 提供对象关系映射标签,支持对象关系组建维护
- 提供
xml
标签,支持编写动态sql
2. 第一个 MyBatis 程序
- 思路:搭建环境 —— 导入 MyBatis —— 编写代码 —— 测试
2.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,'murphy','123123'), (2,'cici','yangqian'), (3,'qianzai','123456');
-
新建项目
-
新建一个普通的
Maven
项目 -
删除
src
目录 -
导入
Maven
依赖<dependencies> <!-- mysql 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
-
2.2 创建模块
-
编写
mybatis
核心配置文件<!-- Core configuration file --> <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=true& characterEncoding=UTF-8&serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="123123"/> </dataSource> </environment> </environments> </configuration> <mappers> <mapper resource="com/murphy/dao/AdminMapper.xml"/> </mappers>
-
编写
mybatis
工具类SqlSession
- 完全包含了面向数据库执行SQL
命令所需的所有方法。
//sqlSessionFactory --> sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { // 使用 Mybatis 第一步: // 获取 sqlSessionFactory 对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // 第二步: // 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession();; } }
2.3 编写代码
-
实体类
// 实体类 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; } }
-
DAO 接口类
public interface UserDAO { List<User> getUserList(); }
-
接口实现类 - 由原本的
UserDaoImpl
转变为一个Mapper
配置文件.<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace - bind relative dao interface --> <mapper namespace="com.murphy.DAO.UserDAO"> <!-- select - query --> <select id="getUserList" resultType="com.murphy.POJO.User"> select * from mybatis.user </select> </mapper>
2.4 测试
-
junit
测试@Test public void test(){ // 1. 获取 sqlSession 对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); // 2. 执行 SQL // 方式一:getMapper UserDAO userDao = sqlSession.getMapper(UserDAO.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } // 3. 关闭 sqlSession sqlSession.close(); }
-
MapperRegister
- 核心配置文件中注册mappers
-
可能遇到的问题:
- 配置文件没有注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
- Maven导出资源问题
3. CRUD
- 编写接口 —— 编写对应的
mapper
中的sql
语句 —— 测试
-
namespace
namespace
中的包名要和DAO/mapper
接口的包名一致!
-
select
-
选择 / 查询语句
-
id
:即对应的namespace
中的方法名; -
resultType
:SQL语句执行的返回值! -
parameterType
:参数类型!// 根据ID查询用户 User getUserById(int id); <select id="getUserById" parameterType="int" resultType="com.murphy.POJO.User"> select * from mybatis.user where id = #{id} </select> @Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO userDAO = sqlSession.getMapper(UserDAO.class); User user = userDAO.getUserById(1); System.out.println(user); }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
-
-
insert
// 增加一个用户(insert) int addUser(User user); <!-- Property of objects can be taken out --> <insert id="addUser" parameterType="com.murphy.POJO.User"> insert into mybatis.user (id, name, pwd) VALUES (#{id},#{name},#{pwd}); </insert> @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO userDAO = sqlSession.getMapper(UserDAO.class); // 增删改查需要提交事务 int res = userDAO.addUser(new User(4,"lucky","123123")); if (res>0){ System.out.println("插入成功!"); } // 提交事务 - 很重要 sqlSession.commit(); }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
update
// 修改用户(update) int updateUser(User user); <update id="updateUser" parameterType="com.murphy.POJO.User"> update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id}; </update> @Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO user = sqlSession.getMapper(UserDAO.class); int res = user.updateUser(new User(4,"xixi","132132")); if (res>0){ System.out.println("修改成功!"); } // 提交事务 sqlSession.commit(); }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
delete
// 删除用户(delete) int deleteUser(int id); <delete id="deleteUser" parameterType="int"> delete from mybatis.user where id = #{id} </delete> @Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO user = sqlSession.getMapper(UserDAO.class); int res = user.deleteUser(4); if (res>0){ System.out.println("删除成功!"); } sqlSession.commit(); }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
标签不要匹配错
resource
绑定mapper
,需要使用路径- 程序配置文件必须符合规范!
NullPointerException
,没有注册到资源- 输出的
xml
文件中存在中文乱码问题 maven
资源没有导出问题
-
万能
Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用
Map
!Map
传递参数,直接在sql
中取出key
即可![parameterType="map"]
- 对象传递参数,直接在
sql
中取对象的属性即可![parameterType="object"]
- 只有一个基本类型参数的情况下,可以直接在
sql
中取到! - 多个参数用
Map
,或者注解!
// 万能的 Map int addUser2(Map<String,Object> map); <!-- 传递map的key --> <insert id="addUser2" parameterType="map"> insert into mybatis.user (id, name, pwd) VALUES (#{userid},#{username},#{password}); </insert> @Test public void addUser2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO mapper = sqlSession.getMapper(UserDAO.class); Map<String, Object> map = new HashMap<String, Object>(); map.put("userid", 5); map.put("username", "hanhan"); map.put("password", "45814581"); mapper.addUser2(map); sqlSession.commit(); }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
模糊查询
-
Java
代码执行的时候,传递通配符% %
List<User> userList = mapper.getUserLike("%han%");
-
在
sql
拼接中使用通配符!select * from mybatis.user where name like "%"#{value}"%"
// 模糊查询 List<User> getUserLike(String value); <select id="getUserLike" resultType="com.murphy.POJO.User"> select * from mybatis.user where name like #{value} </select> @Test public void getUserLike(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO mapper = sqlSession.getMapper(UserDAO.class); List<User> userList = mapper.getUserLike("%han%"); for (User user : userList) { System.out.println(user); } }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
4. 配置解析
-
核心配置文件
-
mybatis-config.xml
-
MyBatis
的配置文件包含了会深深影响MyBatis
行为的设置和属性信息。configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
-
-
环境配置
environments
- 不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true& characterEncoding=UTF-8&serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="123123"/> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true& characterEncoding=UTF-8&serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="123123"/> </dataSource> </environment> </environments>
-
数据源
dataSource
—— 连接数据库dbcp / c3p0 / druid
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。 池:用完可以回收。
学会使用配置多套运行环境!
UNPOOLED - 无连接池 POOLED - 有连接池 JNDI - 正常连接 // 你可以通过实现接口 org.apache.ibatis.datasource.DataSourceFactory 来使用第三方数据源实现: public interface DataSourceFactory { void setProperties(Properties props); DataSource getDataSource(); } // org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory 可被用作父类来构建新的数据源适配器, // 比如下面这段插入 C3P0 数据源所必需的代码: import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0DataSourceFactory extends UnpooledDataSourceFactory { public C3P0DataSourceFactory() { this.dataSource = new ComboPooledDataSource(); } }
-
Mybatis
默认的事务管理器JDBC
,连接池:POOLED
-
属性
properties
- 我们可以通过properties
属性来实现引用配置文件这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
[db.properties]
- 编写一个配置文件 ——
db.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 username=root password=123123
-
在核心配置文件中引入
在
xml
中,所有标签都应该遵守一定的顺序.<!-- Write Properties File --> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="123123"/> </properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
property
元素体内的属性优先,在resource
导入文件中遇到同名属性会覆盖
- 编写一个配置文件 ——
-
类型别名 ——
typeAliases
-
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<typeAliases> <typeAlias type="com.murphy.pojo.User" alias="User"></typeAlias> </typeAliases> <typeAliases> <package name="com.murphy.pojo"/> </typeAliases> import org.apache.ibatis.type.Alias; @Alias("user")
-
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
扫描实体类的包,它的默认别名就为这个类的 类名,首字母小写! / 别名不区分大小写
-
在实体类比较少的时候,使用第一种方式。 / 如果实体类比较多,建议使用第二种。
-
第一种可以 DIY 别名;第二种不行,如果非要改,需要在实体类上增加 注解。
_byte byte _long long _short short _int int _integer int _double double _float float _boolean boolean
-
-
设置
Settings
—— 改变 MyBatis 的运行时行为mapUnderscoreToCamelCase true | false False —— 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。(数据库不区分大小写) safeRowBoundsEnabled true | false False —— 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。
-
其他配置
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
mybatis-generator-core
mybatis-plus
- 通用
mapper
-
映射器
mapper
-
MapperRegister
- 注册绑定我们的mapper
文件 -
方式一:【推荐使用】
<mappers> <mapper resource="com/murphy/dao/UserMapper.xml"/> </mappers>
-
方式二:使用
class
文件绑定注册<mappers> <mapper class="com.murphy.dao.UserMapper"/> </mappers>
-
注意点:
- 接口和
mapper
配置文件必须同名! - 接口和
mapper
配置文件必须在同一个包下!
- 接口和
-
方式三:使用扫描包进行注入绑定
<mappers> <mapper name="com.murphy.dao"/> </mappers>
-
-
生命周期和作用域
-
生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
-
SqlSessionFactoryBuilder
:- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
-
SqlSessionFactory
:- 类比为 数据库连接池
SqlSessionFactory
一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例- 最佳作用域:应用作用域
- 最简单的就是使用单例模式或者静态单例模式
-
SqlSession
-
连接到连接池的一个请求
-
实例不是线程安全的,因此是不能被共享的,用完之后需要关闭,否则资源会被占用
-
这里面的每一个
Mapper
,就代表一个具体的业务!
-
-
5. 解决属性名和字段名不一致的问题
数据库的字段:id / name / pwd
-
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
private int id; private String name; private String password;
-
测试出现问题
User{id=1, name='murphy', password='null'}
-
解决方法:
-
起别名
<select id="getUserById" parameterType="int" resultType="com.murphy.pojo.User"> select id, name, pwd as password from mybatis.user where id = #{id} </select>
-
ResultMap
-
结果集映射
id name pwd id name password <!-- ResultMap --> <resultMap id="UserMap" type="User"> <!-- Database - column / POJO - property --> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap>
-
resultMap
元素是 MyBatis 中最重要最强大的元素。 -
ResultMap
的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
6. 日志
6.1 日志工厂
- 如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
Before: sout / debug
Now: 日志工厂
- SLF4J
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】—— 标准日志输出
- NO_LOGGING
在Mybatis
中具体使用那个日志实现,在设置中设定! - 更改value
值
STDOUT_LOGGING 标准日志输出
- 在
mybatis
核心配置文件中,配置我们的日志!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
Opening JDBC Connection
Created connection 956420404.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3901d134]
==> Preparing: select * from mybatis.user where id = ?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, murphy, xmf199315
<== Total: 1
User{id=1, name='murphy', password='123123'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3901d134]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3901d134]
Returned connection 956420404 to pool.
6.2 Log4j
- 通过使用
Log4j
,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件 - 我们可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志生成的过程
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
-
先导入
LOG4J
的包<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/kuang.log log4j.appender.file.MaxFileSize = 10 MB 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
为日志的实现<<settings> <setting name="logImpl" value="LOG4J"/> </settings>
-
log4j
的使用 —— 直接测试运行[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 1285524499. [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4c9f8c13] [com.murphy.dao.UserDAO.getUserById]-==> Preparing: select * from mybatis.user where id = ? [com.murphy.dao.UserDAO.getUserById]-==> Parameters: 1(Integer) [com.murphy.dao.UserDAO.getUserById]-<== Total: 1 User{id=1, name='murphy', password='123123'} [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4c9f8c13] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4c9f8c13] [org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 1285524499 to pool.
简单使用
-
在要使用
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方法");
7. 分页
作用:
- 减少数据的处理量
7.1 使用 Limit 分页
语法:
SELECT * FROM user limit startIndex, pageSize; # 不包括 startIndex
select * from user limit 3; # [0,N]
7.2 使用 Mybatis 实现分页,核心 SQL
-
接口
// 分页 List<User> getUserByLimit(Map<String,Integer> map);
-
Mapper.xml
<!-- 分页 --> <select id="getUserByLimit" parameterType="map" resultMap="UserMap"> select * from mybatis.user limit #{startIndex},#{pageSize} </select>
-
测试
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ UserDAO mapper = sqlSession.getMapper(UserDAO.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",1); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
7.3 RowBounds 分页
-
不再使用
SQL
实现分页-
接口
// RowBounds 分页 List<User> getUserByRowBounds(Map<String,Integer> map);
-
Mapper.xml
<!-- RowBounds 分页 --> <select id="getUserByRowBounds" resultMap="UserMap"> select * from mybatis.user </select>
-
测试
@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try { // RowBounds 实现 RowBounds rowBounds = new RowBounds(1, 2); // 通过Java代码层面实现分页 List<User> userList = sqlSession.selectList("com.murphy.dao.UserDAO.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
-
7.4 分页插件
PageHelper
: https://pagehelper.github.io/
8. 使用注解开发
8.1 面向接口编程
- 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好。
8.2 面向注解开发
-
接口 —— 注解在接口上实现
@Select("select * from user") List<User> getUsers();
-
需要在核心配置文件中绑定接口
<mappers> <mapper class="com.murphy.dao.UserDAO" /> </mappers>
-
测试
本质:反射机制实现 底层:动态代理! @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ // 底层主要应用反射 UserDAO mapper = sqlSession.getMapper(UserDAO.class); List<User> userList = mapper.getUsers(); for (User user : userList) { System.out.println(user); } }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
8.3 Mybatis 详细的执行流程
Resources
获取加载全局配置文件- 实例化
SqlSessionFactoryBuilder
构造器 - 解析配置文件流
XMLConfigBuilder
Configuration
所有的配置信息SqlSessionFactory
实例化transactional
事务管理- 创建
executor
执行器 - 创建
sqlSession
- 实现
CRUD
—— 回滚 6 - 查看是否执行成功 —— 回滚 6
- 提交事务
- 关闭
8.4 注解 CRUD
-
我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); }
-
编写接口,增加注解
// 方法存在多个参数,所有的参数前面必须加上 @Param("id") 注解 @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);
-
测试类
//C User userById = mapper.getUserById(1); System.out.println(userById); //R mapper.addUser(new User(4,"hahao","123121")); //U mapper.updateUser(new User(4,"hanama","321312")); //D mapper.deleteUser(4);
注意:【我们必须要将接口注册绑定到我们的核心配置文件中!】
8.5 @Param() 注解
- 基本类型的参数或者
String
类型,需要加上 - 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
- 我们在
sql
中引用的就是我们这里的@Param()
中设定的属性名! #{}
- 防止sql
注入,优于${}
9. Lombok
🔗:https://projectlombok.org/
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
-
使用步骤:
-
在
IDEA
中安装Lombok
插件 -
在项目中导入
Lombok
的jar
包<!-- Lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</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 @ExtensionMethod (Experimental, activate manually in plugin settings) Lombok config system Code inspections Refactoring actions (lombok and delombok)
-
-
说明:
@Data :无参构造、get、set、toString、hashcode、equals @AllArgsConstructor :有参构造 @NoArgsConstructor :无参构造
10. 多对一处理
-
多对一:
// mybatis-06 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, 'A老师'); 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', 'xiaoming', '1'); INSERT INTO `student` (`id`, `name`, `tid`) values ('2', 'xiaohong', '1'); INSERT INTO `student` (`id`, `name`, `tid`) values ('3', 'xiaowang', '1'); INSERT INTO `student` (`id`, `name`, `tid`) values ('4', 'xiaoli', '1'); INSERT INTO `student` (`id`, `name`, `tid`) values ('5', 'xiaozhang', '1');
测试环境搭建
- 导入
lombok
- 新建实体类
Teacher
,Student
- 建立
Mapper
接口 - 建立
Mapper.xml
文件 - 在核心配置文件中绑定注册我们的
Mapper
接口或者文件!【可选项】 - 测试查询是否能够成功
按照查询嵌套处理
<!--
思路:
1. 查询所有的学生信息
2. 根据查询出来的学生的tid,寻找对应的老师! - 子查询
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id" />
<result property="name" column="name" />
<!-- 复杂属性单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id = #{id}
</select>
!按照结果嵌套查询
<!-- 按照结果嵌套处理 -->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid, s.name sname, t.name tname
from mybatis.student s, mybatis.teacher t
where s.tid = t.id
</select>
<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>
回顾 Mysql 多对一 查询方式:
- 子查询
- 联表查询
11. 一对多处理
环境搭建
// mybatis-07
// 实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
// 一个老师拥有多个学生
private List<Student> students;
}
!按照结果嵌套处理
<!-- 按结果嵌套查询 -->
<select id="getTeacher1" resultMap="TeacherStudent" >
select s.id sid, s.name sname, t.name tname, t.id tid
from mybatis.student s, mybatis.teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid" />
<result property="name" column="tname" />
<!--
复杂的属性,我们需要单独处理
对象:association 集合:collection javaType="" 指定属性的类型!
集合中的泛型信息,我们使用 ofType 获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{tid}
</select>
小结
- 关联 ——
association
【多对一】 - 集合 ——
collection
【一对多】 javaType
- 指定实体类中属性的类型ofType
- 指定映射到List
或者集合中的pojo
类型,泛型中的约束类型
注意点
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一中,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用
Log4j
- 面试高频:
Mysql
引擎InnoDB
底层原理- 索引
- 索引优化
12. 动态 SQL
- 动态
SQL
就是根据不同的条件生成不同的SQL
语句 if / choose(when, otherwise) / trim(where, set) / foreach
搭建环境
# mybatis-08
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
创建一个基础工程
-
导包
-
编写配置文件
<setting name="mapUnderscoreToCamelCase" value="true"/>
-
编写实体类
@Data public class Blog { private int id; private String title; private String author; private Date createTime; private int views; }
-
编写实体类对应的
Mapper
接口和Mapper.xml
文件-
插入数据
// 插入数据 int addBlog(Blog blog); <insert id="addBlog" parameterType="blog"> insert into mybatis.blog(id, title, author, create_time, views) VALUES(#{id},#{title},#{author},#{createTime},#{views}) </insert> @Test public void addInitBlog(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try { BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setId(IDutils.getId()); blog.setTitle("Mybatis-Learnning"); blog.setAuthor("murphy"); blog.setCreateTime(new Date()); blog.setViews(9999); mapper.addBlog(blog); blog.setId(IDutils.getId()); blog.setTitle("Java-Learnning"); mapper.addBlog(blog); blog.setId(IDutils.getId()); blog.setTitle("Spring-Learnning"); mapper.addBlog(blog); blog.setId(IDutils.getId()); blog.setTitle("Micro-Learnning"); mapper.addBlog(blog); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }
-
查询博客 - IF
// 查询博客
List<Blog> queryBlogIf(Map map);
<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>
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title", "Mybatis-Learnning");
map.put("author", "murphy");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
Choose(when, otherwise)
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// 类似 switch-case —— 满足一个即结束
map.put("title", "Java-Learnning");
// map.put("author", "murphy");
map.put("views", 9999);
List<Blog> blogss = mapper.queryBlogChoose(map);
for (Blog blog : blogss) {
System.out.println(blog);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
Trim (where, set)
<!-- where元素只会在至少有一个子元素的条件返回SQL子句的情况下才插入“where”子句。而且,若语句的开头为“AND”或“OR”,where元素也会将它们去除。 -->
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
<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>
SQL 片段
- 有的时候,我们可能将一些功能的部分抽取出来,方便复用!
- 使用SQL标签抽取公共的部分
- 在需要使用的地方使用
include
标签引用即可
- 注意事项:
- 最好基于单表来定义
SQL
片段! - 不要存在
where
标签
- 最好基于单表来定义
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
foreach
select * from user where 1=1 and
<foreach item="id" collection="ids"
open="(" separator="or" close=")">
#{id}
</foreach>
(id=1 or id=2 or id=3)
_____________________________________________________________________________________________________________
// 查询第1-2-3号记录的博客
List<Blog> queryBlogForeach(Map map);
<!--
select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
传递万能Map, map可以存在一个集合
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach item="id" collection="ids" open="and (" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
-
你可以将任何可迭代对象(如
List、Set
等)、Map
对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index
是当前迭代的序号,item
的值是本次迭代获取到的元素。当使用Map
对象(或者Map.Entry
对象的集合)时,index
是键,item
是值。 -
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
-
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
-
建议:
- 先在MySQL中写出完整的SQL,再对应去修改成为我们的动态SQL,实现通用即可。
13. 缓存
简介
查询 —— 连接数据库 —— 消耗资源
一次查询的结果,给他暂存再一个可以直接取到的地方! ——> 内存 :缓存查询
再次查询相同数据的时候,直接走缓存,就不用走数据库了
- 什么是缓存[ Cache ]?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘(关系型数据库数据文件)上查
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
Mybatis 缓存
- Mybatis 包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- Mybatis 系统中默认定义了两级缓存:一级缓存 和 二级缓存。
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,称为本地缓存)
- 二级缓存需要手动开启和配置,基于
namespace
级别的缓存 - 为了提高扩展性,Mybatis 定义了缓存接口
Cache
。我们可以通过实现Cache
接口来自定义二级缓存
一级缓存
- 即 本地缓存
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没有必要再去查询数据库。
测试步骤:
-
开启日志!
-
测试在一个Session中查询两次相同记录
@Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); System.out.println("================="); User user1 = mapper.queryUserById(1); System.out.println(user1); System.out.println(user==user1); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }
-
查看日志输出
缓存失效的情况
-
查询不同的地方
-
增删改操作,可能会改变原来的操作,所以必定刷新缓存!
-
查询不同的
Mapper.xml
-
手动清理缓存!
sqlSession.clearCache();
**小结:**一级缓存是默认开启的,只有一次SqlSession
中有效,也就是拿到连接到关闭连接这个区间段!类似Map
二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存;
- 基于
namespace
级别的缓存,一个名称空间,对应一个二级缓存; - 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的
mapper
查出的数据会放在自己对应的缓存(map)
中;
步骤:
-
开启全局缓存
<setting name="cacheEnabled" value="true"/>
-
在要使用二级缓存的
Mapper
中开启<cache/> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> 也可以自定义参数
-
测试
-
问题:我们需要将实体类 序列化!否则就会报错
Caused by: java.io.NotSerializableException: com.murphy.pojo.user public class User implements Serializable
-
小结:
- 只要开启了二级缓存,在同一个
Mapper
下就有效 - 所有的数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存
缓存原理
自定义缓存 ehcache
Ehcache
是一种广泛应用的开源Java分布式缓存。主要面向缓存
运用:
-
导包
<dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.1.0</version> </dependency>
-
开启缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
-
配置文件 - ehcache.xml