1、简介
MyBatis-Plus 是基于Mybatis的一个工具,它是对MyBatis的增强,在其基础上只进行增强,不进行改变,是为了简化MyBatis开发,提高效率而研发的。
它基于MyBatis 在 Mapper 接口和 Servcie 接口上进行了封装,我们只需要在Mapper接口、Service接口上继承封装的相关接口,即可在没有写任何映射方法的时候,直接使用一些简单的 CRUD 等SQL操作。

- 无侵入:在MyBatis基础上只做增强不做改变,引入它不会对现有工程产生影响。
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作。
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
2、项目整合
2.1、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> <!--setting设置--> <settings> <!--日志STDOUT_LOGGING和LOG4J--> <setting name="logImpl" value="LOG4J"/> </settings> <!--设置别名 --> <typeAliases> <package name="com.yu.mybatisplustest.entity"/> </typeAliases> </configuration>
-
Spring-config.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--包的扫描--> <context:component-scan base-package="com.yu.mybatisplustest"/> <!--支持 @Resource等注解--> <context:annotation-config/> <!--导入数据文件database.properties--> <context:property-placeholder location="classpath:database.properties"/> <!--配置druid 连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!--初始连接数--> <property name="initialSize" value="${jdbc.initialSize}"/> <!--最小空闲连接数--> <property name="minIdle" value="${jdbc.minIdle}"/> <!--最大活动连接数--> <property name="maxActive" value="${jdbc.maxActive}"/> <!--最大等待时间--> <property name="maxWait" value="${jdbc.maxWait}"/> <property name="filters" value="${jdbc.filters}"/> </bean> <!--配置sqlSessionFactory工厂--> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!--加载连接池--> <property name="dataSource" ref="dataSource"/> <!--加载mybatis配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--加载映射文件路径--> <property name="mapperLocations" value="classpath:mapping/*.xml"/> </bean> <!--扫描的mapper接口(也可以使用@Mapper或@MapperScan)--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫描mapper接口所在的包--> <property name="basePackage" value="con.yu.ssmtest.mapper"/> </bean> </beans>
-
log4j日志
#将等级为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=%d{yyyy-MM-dd HH:mm:ss} [%t] [%c] [%p] -%m%n #文件输出的相关设置 #log4j.appender.file = org.apache.log4j.RollingFileAppender #log4j.appender.file.File= #log4j.appender.file.MaxFileSize=10mb #log4j.appender.file.Threshold=DEBUG #log4j.appender.file.layout=org.apache.log4j.PatternLayout #log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] [%c] [%p] -%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
-
实体类
@Data public class User { private Integer userId; private String username; private String password; private Boolean deleted; }
-
Mapper接口和XML映射文件
public interface UserMapper { User selectByPrimaryKey(Integer userId); }
<?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.yu.ssmtest.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.yu.ssmtest.entity.User"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="deleted" jdbcType="BIT" property="deleted" /> </resultMap> <sql id="Base_Column_List"> user_id, username, `password`, deleted </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> <!--@mbg.generated--> select <include refid="Base_Column_List" /> from `user` where user_id = #{userId,jdbcType=INTEGER} </select> </mapper>
-
测试
@SpringJUnitConfig(locations = {"classpath:applicationContext.xml"}) public class SsmTest { @Resource private UserMapper userMapper; @Test public void test(){ User user = userMapper.selectByPrimaryKey(1); System.out.println(user); } }
2.2、MyBatis-Plus配置
使用Spring整合MyBatis-Plus,原来的Mybatis配置只需要极少的更改就可以直接使用了,但是在导入依赖后需要去掉 原来的MyBatis以及Spring整合MyBatis的依赖,否则可能会出现版本冲突,因为MyBatis-Plus的依赖会自动导入mybatis的两个依赖。
MyBatis-Plus3基于JDK8及其以上版本,并提供了 lambda 形式的调用。
<!--mybatis-plus 依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.2</version>
</dependency>
既然MyBatis-Plus 是在mybatis的基础进行增强的,那么自然不需要过多的更改mybatis的配置,基本上只需要更改配置 的sqlSessionFactory工厂 即可使用
。
而 MyBatis-Plus 在使用时最大的改变是它提供的 BaseMapper 接口,内部封装了很多 CURD 的相关操作,这样我们就不用编写 方法映射 和 SQL 相关代码,即可使用大部分的 CURD 操作。
-
mybatis-config.xml配置文件不需要更改
-
Spring-config.xml配置:
只需要将mybatis里的 sqlSessionFactory工厂更改为MyBatis-Plus的即可
,其余的不变org.mybatis.spring.SqlSessionFactoryBean 更改为 com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean
<!--配置Mybatis-plus的--> <bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <!--加载连接池--> <property name="dataSource" ref="dataSource"/> <!-- 设置MyBatis配置文件的路径(可以不设置) --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--加载映射文件路径--> <property name="mapperLocations" value="classpath:mapping/*.xml"/> </bean>
-
log4j日志 不变
-
实体类:这里需要注意一下,因为需要使用BaseMapper 内置的方法,
所以需要在主键上添加一个注解 @TableId,来表示该属性对应主键ID,防止在使用时出现: Invalid bound statement (not found) 异常。
@Data public class User { @TableId private Integer userId; private String username; private String password; private Boolean deleted; }
-
Mapper接口和XML映射文件:在MyBatis-Plus 中提供了一个接口 BaseMapper,这个接口封装了一些简单的CRUD 操作,只需要用 mapper 接口继承 BaseMapper 后,一个方法不用映射也可以实现 CRUD的操作
public interface UserMapper extends BaseMapper<User> { }
<?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.yu.mybatisplustest.mapper.UserMapper"> </mapper>
-
测试:在 mapper接口和映射文件不创建任何映射方法,测试查询
@SpringJUnitConfig(locations = {"classpath:applicationContext.xml"}) public class MybatisplusTest { @Resource private UserMapper userMapper; @Test public void test2(){ //selectById是BaseMapper中封装的方法 User user = userMapper.selectById(1); System.out.println(user); } }