1.1mybatis-plus简介
MyBatis-Plus(简称 MP),是一个 MyBatis 的增强工具包,只做增强不做改变. 为简化开发工作、提高生产率而生。我们的愿景是成为 Mybatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
特性:
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
1.2 ssmp整合
- 引入相关坐标(创建数据库)
<!--版本锁定-->
<properties>
<spring.version>5.3.2</spring.version>
<slf4j.version>1.7.30</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-springMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!--servlet-jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--json的包mvc返回json数据-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
</dependencies>
- 创建实体类和spring配置文件
package com.veo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
/**
* (User)实体类
*
* @author makejava
* @since 2021-01-01 20:55:05
*/
//@TableName(value = "user")
public class User implements Serializable {
private static final long serialVersionUID = 228195023307246450L;
/**
* @TableId:
* value: 指定表中的主键列的列名, 如果实体属性名与列名一致,可以省略不指定.
* type: 指定主键策略.
* AUTO(0)
* NONE(1)
* INPUT(2)
* ASSIGN_ID(3)
* ASSIGN_UUID(4)
* 如果进行了全局配置主键方式可以不配置此注解,(二选一)不配置报错
*/
// @TableId(type = IdType.AUTO,value = "id")
private Integer id;
/**
* @TableField:
* value:与表字段相对应
* exist:表示该属性在数据库中不存在,该属性不会插入数据库
*/
// @TableField(value = "name",exist = false)
private String name;
private String gender;
private Integer age;
private String address;
private String qq;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", address='" + address + '\'' +
", qq='" + qq + '\'' +
", email='" + email + '\'' +
'}';
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置spring的注解扫描-->
<context:component-scan base-package="com.veo">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置数据库文件的加载路径-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置mybatis-plus的sqlSessionFactory-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!--将DataSource注入SqlSessionFactoryBean-->
<property name="dataSource" ref="dataSource"/>
<!--注入全局配置到SqlSessionFactoryBean-->
<property name="globalConfig" ref="globalConfig"/>
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<!--将dbConfig配置到全局配置器-->
<property name="dbConfig" ref="dbConfig"/>
<!--将mySqlInjector配置到全局配置器-->
<property name="sqlInjector" ref="mySqlInjector"/>
</bean>
<!--将自定义批量插入方法注入ioc-->
<bean id="mySqlInjector" class="com.veo.config.MySqlInjector"/>
<!--配置与mybatis-plus数据库相关的配置信息-->
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<!--配置主键为自动增长-->
<property name="idType" value="AUTO"/>
<!--配置表的前缀-->
<!-- <property name="tablePrefix" value="tb_"/>-->
<!--配置数据库的名称-->
<property name="schema" value="ssm6"/>
<!--是否使用驼峰转下划线命名,只对表名生效-->
<property name="tableUnderline" value="true"/>
</bean>
<!--将接口注入IOC容器中为service提供依赖注入-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.veo.mapper"/>
</bean>
<!--配置事务-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--配置注解扫描-->
<context:component-scan base-package="com.veo.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置注解扫描-->
<mvc:annotation-driven/>
<!--配置静态资源不过滤-->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/fonts/" mapping="/fonts/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!--配置aop的注解扫描-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
- 创建mapper接口和配置sql注入配置
配置实体类mapper接口继承BaseMapper类以实现基本增删改方法
package com.veo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.veo.entity.User;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
//定义批量插入的方法
int insertBatchSomeColumn(List<User> entityList);
//定义修改部分列的方法
int alwaysUpdateSomeColumnById(User entity);
int deleteByIdWithFill(User entity);
}
配置sql注入配置文件(扩展实体类的批量删除和修改部分例的扩展方法):
package com.veo.config;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import com.baomidou.mybatisplus.extension.injector.methods.LogicDeleteByIdWithFill;
import java.util.List;
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methods= super.getMethodList(mapperClass);
//加入扩展的方法
methods.add(new InsertBatchSomeColumn());
methods.add(new AlwaysUpdateSomeColumnById());
methods.add(new LogicDeleteByIdWithFill());
return methods;
}
}
5.测试mybatis-plus常用方法
package com.veo.mybatis;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.veo.entity.User;
import com.veo.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext.xml"})
public class SampleTest {
@Autowired
private DataSource dataSource;
@Autowired
private UserMapper userMapper;
/**
* 测试数据库连接池是否连接成功
* @throws SQLException
*/
@Test
public void testDataSource() throws SQLException {
System.out.println(dataSource.getConnection());
}
@Test
public void testInsert(){
User user=new User();
user.setName("大王");
user.setAge(25);
user.setGender("男");
user.setAddress("北京");
user.setQq("123456");
user.setEmail("[email protected]");
//insert方法在插入时, 会根据实体类的每个属性进行非空判断,
//只有非空的属性对应的字段才会出现到SQL语句中,为空默认插入null
int result = userMapper.insert(user);
System.out.println("result:"+result);
}
@Test
public void testInsertBatch(){
User user1=new User();
user1.setName("小王");
User user2=new User();
user2.setName("中王");
User user3=new User();
user3.setName("大王");
List<User> userList=new ArrayList<>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
//批量插入数据
int i = userMapper.insertBatchSomeColumn(userList);
System.out.println("insertBatch:"+i);
}
@Test
public void testUpdateById(){
User user=new User();
user.setId(36);
user.setName("小龙女");
user.setAge(18);
user.setGender("女");
//根据id进行更新
int update = userMapper.updateById(user);
System.out.println("updateResult:"+update);
}
@Test
public void testUpdateByCondition(){
User user=new User();
user.setName("小龙女");
user.setGender("女");
//条件更新数据(没有条件默认更新数据库中的所有数据)
//UPDATE user SET name=?, gender=? WHERE (id = ? AND qq LIKE ?)
QueryWrapper<User> wrapper=new QueryWrapper<User>();
wrapper.eq("id","35");
wrapper.like("qq","123");
int update = userMapper.update(user, wrapper);
System.out.println("updateResult:"+update);
}
@Test
public void testDelete(){
QueryWrapper<User> wrapper=new QueryWrapper<User>();
User user=new User();
user.setName("小龙女");
user.setGender("女");
wrapper.setEntity(user);
//根据传入的user进行条件删除
int i = userMapper.delete(wrapper);
System.out.println("delete:"+i);
}
@Test
public void testDeleteBatch(){
//根据id进行批量删除
int i = userMapper.deleteBatchIds(Arrays.asList("1","2","3"));
System.out.println("delete:"+i);
}
@Test
public void testDeleteById(){
//根据id进行删除
int i = userMapper.deleteById(1);
System.out.println("delete:"+i);
}
@Test
public void testDeleteByCondition(){
//根据map条件进行删除(键名与数据库的字段名相同)
Map<String,Object> map=new HashMap<String, Object>();
map.put("name","小王");
map.put("id","5");
int i = userMapper.deleteByMap(map);
System.out.println("delete:"+i);
}
/**
* 查询所有数据(或条件查询数据)
*/
@Test
public void testSelectAll(){
//无条件查询所有
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
//条件查询
QueryWrapper<User> wrapper=new QueryWrapper<User>();
wrapper.eq("gender","女");
wrapper.like("name","张");
wrapper.le("age",25);
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
@Test
public void testSelectById(){
User user=new User();
user.setId(12);
//根据id查询数据
User user1 = userMapper.selectById(user);
System.out.println(user1);
}
@Test
public void testSelectOne(){
//查询单一数据
QueryWrapper<User> wrapper=new QueryWrapper<User>();
wrapper.eq("id","11");
User user = userMapper.selectOne(wrapper);
System.out.println(user);
}
@Test
public void testSelectPage(){
//分页查询
Page<User> page=new Page<User>(3,3);
QueryWrapper<User> wrapper=new QueryWrapper<User>();
wrapper.eq("gender","女");
wrapper.orderByDesc("age");
Page<User> userPage = userMapper.selectPage(page, wrapper);
List<User> records = userPage.getRecords();
records.forEach(System.out::println);
System.out.println("总记录数:"+userPage.getTotal());
System.out.println("每页的数量:"+userPage.getSize());
System.out.println("共几页:"+userPage.getPages());
System.out.println("当前:"+userPage.getCurrent());
}
}
整合要点
-
坐标导入无需导入spring和mybatis和整合坐标,以及mybatis的坐标,只需导入mybatis-plus的坐标(mybatis-plus中整合了mybatis和spring的jar包)
-
spring的配置文件中注入的sqlSessionFactoryBean换成
com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean
-
定义实体类mapper接口实现BaseMapper类,自定义和扩展的配置类要注入IOC容器后再注入到
com.baomidou.mybatisplus.core.config.GlobalConfig
的全局配置类中,在注入到com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean
mybatis-plus的sqlSessionFactoryBean中,这样自定义的配置文件才会生效 -
要进行基本增删改要定义id的主键生成类型(二选一)
注解方式:
@TableName(value = "user")
public class User implements Serializable {
private static final long serialVersionUID = 228195023307246450L;
/**
* @TableId:
* value: 指定表中的主键列的列名, 如果实体属性名与列名一致,可以省略不指定.
* type: 指定主键策略.
* AUTO(0)
* NONE(1)
* INPUT(2)
* ASSIGN_ID(3)
* ASSIGN_UUID(4)
* 如果进行了全局配置主键方式可以不配置此注解,(二选一)不配置报错
*/
@TableId(type = IdType.AUTO,value = "id")
private Integer id;
/**
* @TableField:
* value:与表字段相对应
* exist:表示该属性在数据库中不存在,该属性不会插入数据库
*/
@TableField(value = "name",exist = false)
private String name;
全局配置方式:
<!--配置mybatis-plus的sqlSessionFactory-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!--将DataSource注入SqlSessionFactoryBean-->
<property name="dataSource" ref="dataSource"/>
<!--注入全局配置到SqlSessionFactoryBean-->
<property name="globalConfig" ref="globalConfig"/>
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<!--将dbConfig配置到全局配置器-->
<property name="dbConfig" ref="dbConfig"/>
<!--将mySqlInjector配置到全局配置器-->
<property name="sqlInjector" ref="mySqlInjector"/>
</bean>
<!--将自定义批量插入方法注入ioc-->
<bean id="mySqlInjector" class="com.veo.config.MySqlInjector"/>
5.要将创建的实体类mapper接口注入spring的IOC容器,否则会注入不成功
<!--将接口注入IOC容器中为service提供依赖注入-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.veo.mapper"/>
</bean>