MyBatisPlus_集成Spring 的环境搭建,以及测试
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
前置知识
MyBatis
Spring
Maven
第一个MyBatis程序
- 搭建开发环境
//在maven pom文件中导入以下依赖 需要注意的是使用mybatisplus 不需要导入mybatis相关依赖,以及Spring集成mybatis相关,避免jar包冲突,mybatisplus会自动维护
<dependencies>
<!-- junit 测试jar-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--导入mybatis plus 相关依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.2</version>
</dependency>
<!-- 导入日志jar -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 导入连接池相关jar -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- 导入mysql 链接jar-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- spring 集成相关jar-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
</dependencies>
- 引入配置文件
log4j配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
applicationContext.xml Spring配置文件
需要注意的是当前在Spring的配置文件中的sqlsession 对象需要使用MyBatisPlus的
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置对应的url -->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/soft"></property>
<!-- 配置驱动-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<!-- 数据库用户名-->
<property name="user" value="root"></property>
<!-- 数据库密码-->
<property name="password" value="root"></property>
</bean>
<!-- 使用mybatisplus的MyBaitsSqlSessionFactoryBean -->
<bean id="sqlsessionfactorybuilder" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!-- 引入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 指定配置文件路径-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- 创建mapperscannerConfig -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.tedu.dao"></property>
</bean>
</beans>
- MyBatis的配置文件直接导入即可
测试当前MyBatisPlus当前配置的数据库链接是否链接成功
@Test
public void test() throws SQLException {
//通过spring 工厂读取配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过工厂类创建当前的数据源对象
DataSource da = ac.getBean("dataSource", DataSource.class);
//答应输出当前数据源中的链接对象 测试当前的数据库链接是否成功
System.out.println(da.getConnection());
}
MyBaits 开发需要定义一个接口,以及对应的映射文件。以及接口中的方法所对应的SQL语句
MyBaitsPlus: 则需要使当前的接口继承自MyBatisPlus提供的一个接口BaseMapper
/*
* Copyright (c) 2011-2021, baomidou (jobob@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baomidou.mybatisplus.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/*
:`
.:,
:::,,.
:: `::::::
::` `,:,` .:`
`:: `::::::::.:` `:';,`
::::, .:::` `@++++++++:
`` :::` @+++++++++++#
:::, #++++++++++++++`
,: `::::::;'##++++++++++
.@#@;` ::::::::::::::::::::;
#@####@, :::::::::::::::+#;::.
@@######+@:::::::::::::. #@:;
, @@########':::::::::::: .#''':`
;##@@@+:##########@::::::::::: @#;.,:.
#@@@######++++#####'::::::::: .##+,:#`
@@@@@#####+++++'#####+::::::::` ,`::@#:`
`@@@@#####++++++'#####+#':::::::::::@.
@@@@######+++++''#######+##';::::;':,`
@@@@#####+++++'''#######++++++++++`
#@@#####++++++''########++++++++'
`#@######+++++''+########+++++++;
`@@#####+++++''##########++++++,
@@######+++++'##########+++++#`
@@@@#####+++++############++++;
;#@@@@@####++++##############+++,
@@@@@@@@@@@###@###############++'
@#@@@@@@@@@@@@###################+:
`@#@@@@@@@@@@@@@@###################'`
:@#@@@@@@@@@@@@@@@@@##################,
,@@@@@@@@@@@@@@@@@@@@################;
,#@@@@@@@@@@@@@@@@@@@##############+`
.#@@@@@@@@@@@@@@@@@@#############@,
@@@@@@@@@@@@@@@@@@@###########@,
:#@@@@@@@@@@@@@@@@##########@,
`##@@@@@@@@@@@@@@@########+,
`+@@@@@@@@@@@@@@@#####@:`
`:@@@@@@@@@@@@@@##@;.
`,'@@@@##@@@+;,`
``...``
_ _ /_ _ _/_. ____ / _
/ / //_//_//_|/ /_\ /_///_/_\ Talk is cheap. Show me the code.
_/ /
*/
/**
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* <p>这个 Mapper 支持 id 泛型</p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
<E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
查看当前BaseMapper中的所有方法 alt+7
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RgsYyDKa-1626677402519)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210713113804926.png)]
使用MyBatisPlus来对当前数据库中的表进行修改
- 首先定义对应的dao接口 让当前接口继承自MyBatisPlus中的一个叫做BaseMapper的接口 在当前DAO接口中无需定义任何方法
- 使用Spring的工厂类对象将当前的DAO对象创建
- 调用当前DAO接口中继承自BaseMapper中的方法来完成对数据库的操作
@Test
public void test1(){
//通过spring 工厂读取配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//创建当前的DAO接口类对象 指定当前的bean id 为当前接口首字母小写作为beanid
// 第二个参数指定当前工厂创建的对象为指定对象类型
StudentDAO dao = ac.getBean("studentDAO", StudentDAO.class);
//创建实体类对象作为插入数据的参数
Student student = new Student(2, "av", "aaaa", 100.0, 11);
//调用当前的接口中的insert 方法来完成对数据库中的数据插入操作
//当前方法的返回值是一个int 类型 代表当前对数据库中的数据影响的条数
int result = dao.insert(student);
//答应输出当前对数据库中影响的条数
System.out.println("result+"+result);
}
MyBatisPlus中的注解
TableId
value:用来指定当前表中字段与实体类中字段不一致时需要通过设置value来指定字段值 如果表中字段与实体类中属性值相等,则不需要为当前value进行赋值
type: 代表当前的表中的id值需要采用哪一种提交策略
TableName
value:mybatisplus会默认将当前的实体类的类名作为当前操作表的表名,如果发生实体类中的类名与当前表中的表名不一致,则需要使用value来进行表名的指定
type:指定resultMap结果集处理
TableFiled
value:用来指定当前实体类中的属性名称与当前表中字段不一致问题
exits:用来忽略某些字段 。如果当前实体类中的属性在表中不存在对应的字段,则需要通过exits来指定当前属性不参与CRUD操作
注解加载实体类中
//MyBatisPlus默认将当前的实体类类名作为表名进行CRUD操作
//如果当前实体类与表名不一致时,则需要通过TableName来指定表名
@TableName(value = "student")
public class Student implements Serializable {
//value 代表当前实体类中的属性名称与表中的字段不匹配时使用value来对应关系
//type代表当前id 的提交方式
@TableId(type = IdType.AUTO)
private int id;
private String name;
private String password;
private Double salary;
private int age;
}
MyBatisPlus的全局策略
作用:使用如上注解只能针对单独的实体类进行设置,配置全局策略则可以统一对多个实体类进行配置
需要在当前Spring的配置文件中进行相关配置
需要注意的是当前的MyBatisPlus的全局策略配置完成后需要在当前MyBatisSqlSessionFactoryBean
中来进行引入工作
<!-- 使用mybatisplus的MyBaitsSqlSessionFactoryBean -->
<bean id="sqlsessionfactorybuilder" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!-- 引入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 指定配置文件路径-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 将当前的全局策略引入当前的mybatis 中 -->
<property name="globalConfig" ref="dbConfig"></property>
</bean>
<!-- 配置mybatis plus 的全局策略 -->
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig" ref="Dbconfig"></property>
</bean>
<bean id="Dbconfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<!-- 将当前实体类中的驼峰命名属性与表中下划线字段名称进行匹配 默认值为true -->
<property name="tableUnderline" value="true"></property>
<!-- 设置当前实体类提交时id策略 取代TableId注解设置-->
<property name="idType" value="AUTO"></property>
<!-- 设置当前实体类名与数据库表名不一致时取代TableName注解设置 代表当前表名的前缀例如 tab_Student -->
<property name="tablePrefix" value=""></property>
</bean>
MyBatisPlus CRUD操作
MyBatisPlus 插入操作
MyBaitsPlus在插入数据到数据库中的同时还可以获取当前插入数据的主键值
public void test1() {
//通过spring 工厂读取配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//创建当前的DAO接口类对象 指定当前的bean id 为当前接口首字母小写作为beanid
// 第二个参数指定当前工厂创建的对象为指定对象类型
StudentDAO dao = ac.getBean("studentDAO", StudentDAO.class);
//创建实体类对象作为插入数据的参数
Student student = new Student();
student.setName("阿伟");
student.setAge(12);
student.setSalary(100.0);
student.setPassword("aaa");
//调用当前的接口中的insert 方法来完成对数据库中的数据插入操作
//当前方法的返回值是一个int 类型 代表当前对数据库中的数据影响的条
int result = dao.insert(student);
//答应输出当前对数据库中影响的条数
System.out.println("result+" + result);
//获取当前插入对象在数据库中的主键值
int ud = student.getId();
System.out.println(ud);
}
MyBatisPlus 更新操作
根据id来对当前数据库中的数据进行修改
@Test
public void test1() {
//通过spring 工厂读取配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//创建当前的DAO接口类对象 指定当前的bean id 为当前接口首字母小写作为beanid
// 第二个参数指定当前工厂创建的对象为指定对象类型
StudentDAO dao = ac.getBean("studentDAO", StudentDAO.class);
//创建实体类对象作为插入数据的参数
Student student = new Student();
student.setName("aaaaa");
student.setId(5);
student.setAge(12);
student.setSalary(100.0);
student.setPassword("aaa");
//将当前对象中的属性值更新到数据库中
dao.updateById(student);
}
使用条件构造器进行数据库中的数据更新
作用:给sql多个条件来对数据库中的数据进行修改
@Test
public void test1() {
//通过spring 工厂读取配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//创建当前的DAO接口类对象 指定当前的bean id 为当前接口首字母小写作为beanid
// 第二个参数指定当前工厂创建的对象为指定对象类型
StudentDAO dao = ac.getBean("studentDAO", StudentDAO.class);
//创建实体类对象作为插入数据的参数
Student student = new Student();
student.setName("阿伟");
student.setId(5);
student.setAge(12);
student.setSalary(100.0);
student.setPassword("aaa");
//创建条件构造器
//第一种创建条件构造器方式
// UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
//第二种创建条件构造器方式
UpdateWrapper<Student> updateWrapper = Wrappers.update();
//第三种创建条件构造器方式
// LambdaUpdateWrapper<Student> updateWrapper = Wrappers.lambdaUpdate();
// updateWrapper.set(Student::getAge,12);
// updateWrapper.set(Student::getName,"拉曼大表达式");
updateWrapper.eq("name","拉曼大表达式");
/**
* 构造器设置条件更新
* update(user, update);
* 其中 第一个参数user为SQL中为set中要设置的参数
* 第二个参数update为SQL中where中的条件
*/
//修改操作
//dao.update(null, updateWrapper);
dao.update(student,updateWrapper);
}
MyBatisPlus 查询操作
//查询操作
//创建条件构造器
QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("password", "eee");
//1.根据当前id作为条件来查询数据库对象
Student stu = dao.selectById(5);
//2.根据条件构造器查询当前符合条件的数据有几条
Integer integer = dao.selectCount(queryWrapper);
//3.根据条件构造器查询多个对象
List<Student> students = dao.selectList(queryWrapper);
students.forEach(a-> System.out.println(a));
//4.根据条件构造器查询一个对象出来
Student stu = dao.selectOne(queryWrapper);
System.out.println(stu);
//5.根据map集合中指定的键值对来对于当前数据库中的数据进行查询
//map集合中的键值对 key 代表当前数据库中的列名 value代表当前sql中where 的条件
HashMap<String, Object> map = new HashMap<>();
map.put("name", "阿伟");
map.put("age", 12);
//调用当前方法传入map集合来完成相应的查询工作
List<Student> stu = dao.selectByMap(map);
stu.forEach(o -> System.out.println(o));
//6.分页查询数据
Page<Student> p = dao.selectPage(new Page<>(2, 2), null);
System.out.println(p.getRecords());
MyBatisPlus 删除操作
//删除操作
//1.根据id删除当前数据库中的数据
int u = dao.deleteById(2);
System.out.println(u);
//2.根据条件构造器删除对应的数据
UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name", "阿伟");
updateWrapper.eq("age", 12);
dao.delete(updateWrapper);
//3.根据map集合作为参数来删除对应的数据 map key 作为列名 value 作为SQL中的where 条件值
HashMap<String, Object> map = new HashMap<>();
map.put("name", "阿伟");
map.put("age", 1);
dao.deleteByMap(map)
//4.根据集合,在集合中指定要删除的条件,将当前的条件作为参数传入当前的方法中完成操作
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(6);
list.add(8);
dao.deleteBatchIds(list);
总结:基本的CRUD操作。MyBatisPlus使用过程中只需要通过为当前接口继承一个BaseMapper
接口就会有若干个方法供我们对于数据库进行操作,现如今我们基本可以不去书写任何SQL命令就可以完成对传统过的数据库进行增删改查操作
updateWrapper.eq(“name”, “阿伟”);
updateWrapper.eq(“age”, 12);
dao.delete(updateWrapper);
//3.根据map集合作为参数来删除对应的数据 map key 作为列名 value 作为SQL中的where 条件值
HashMap<String, Object> map = new HashMap<>();
map.put(“name”, “阿伟”);
map.put(“age”, 1);
dao.deleteByMap(map)
//4.根据集合,在集合中指定要删除的条件,将当前的条件作为参数传入当前的方法中完成操作
ArrayList list = new ArrayList();
list.add(6);
list.add(8);
dao.deleteBatchIds(list);
总结:基本的CRUD操作。MyBatisPlus使用过程中只需要通过为当前接口继承一个`BaseMapper`接口就会有若干个方法供我们对于数据库进行操作,现如今我们基本可以不去书写任何SQL命令就可以完成对传统过的数据库进行增删改查操作