Mybatis-Plus系统化学习之环境准备与简单使用
1.背景
平时在开发中会经常用到单表的CRUD操作
其实,这些单表的CRUD,完全不需要我们写sql,可以使用mybatis-plus自动生成,不但高效而且不容用出错!
2.mybatis-plus的强大
mybatis可以根据数据库的设计一键生成实体、mapper、service、controller,
如果自己定义了模板,还可以实现对单表的上传、下载、单表的接口访问等
3.环境准备springboot整合mybatis-plus
1.准备数据库,示例中数据库名称为mp-data
2.导入数据到mp-data中用于测试使用
案例中以系统用户为例讲解,导入数据脚本如下
/* Navicat MySQL Data Transfer Source Server : 127.0.0.1 Source Server Version : 50525 Source Host : localhost:3306 Source Database : mp-data Target Server Type : MYSQL Target Server Version : 50525 File Encoding : 65001 Date: 2020-11-06 21:40:57 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for sys_user -- ---------------------------- DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` int(32) NOT NULL AUTO_INCREMENT COMMENT '主键', `name` varchar(64) DEFAULT NULL, `version` int(64) DEFAULT NULL, `gender` int(32) DEFAULT NULL, `age` int(32) DEFAULT NULL, `position` varchar(64) DEFAULT NULL, `account` varchar(255) DEFAULT NULL, `password` varchar(225) DEFAULT NULL, `status` varchar(64) DEFAULT NULL, `create_time` datetime DEFAULT NULL, `type` varchar(64) DEFAULT NULL COMMENT '类型', `update_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of sys_user -- ---------------------------- INSERT INTO `sys_user` VALUES ('1', '张九', '3', '0', '100', '运维部经理', 'sff', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('2', '李四', '2', '0', '45', '项目经理', 'agfsg', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('3', '王五', '4', '0', '76', '项目经理', 'asgag', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('4', '赵六', '5', '0', '12', '运维工程师', '5sf', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('5', '张无忌', null, '0', '15', '运维工程师', 'as5f', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('6', '赵敏', null, '1', '14', '运维工程师', 'asefga45', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('7', '金毛狮王', null, '1', '45', '运维工程师', '54a5', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('8', '孙悟空', null, '1', '76', '运维工程师', '64asf', '123456', '启用', '2019-01-12 12:00:00', null, null); INSERT INTO `sys_user` VALUES ('9', '猪八戒', null, '1', '14', '运维工程师', 'asg45', '123456', '启用', '2019-01-12 12:00:00', null, null);
3.构建springboot maven项目,名称为mp-demo,结构如下
4.引入pom.xm中引入jar包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.ldp</groupId> <artifactId>mp-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mp-demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <!--链接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.2</version> </dependency> <!-- mybatis-plus包--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <!--数据库驱动包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <!-- xml放在java目录下--> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!--指定资源的位置(xml放在resources下,可以不用指定)--> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </project>
5.springboot主配置文件application.yml,其中有mybatis-plus的配置,有说明认真看一下,如下
# 配置端口 server: port: 8099 servlet: context-path: /api spring: # 配置数据源 datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mp-data?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai& username: root password: admin # mybatis-plus相关配置 mybatis-plus: # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置) mapper-locations: classpath:mapper/*.xml # 以下配置均有默认值,可以不设置 global-config: db-config: #主键类型 AUTO:"数据库ID自增" INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; id-type: auto #字段策略 IGNORED:"忽略判断" NOT_NULL:"非 NULL 判断") NOT_EMPTY:"非空判断" field-strategy: NOT_EMPTY #数据库类型 db-type: MYSQL configuration: # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射 map-underscore-to-camel-case: true # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段 call-setters-on-nulls: true # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl logging: config: classpath:logback.xml
6.日志文件logback.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/defaults.xml"/> <!-- 定义日志的根目录 --> <property name="LOG_HOME" value="logs"/> <!-- 控制台输出 --> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>DEBUG</level> </filter> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}-[%t]-[ %-5level ] [ %logger{50} ] - %msg%n</pattern> <charset>utf8</charset> </encoder> </appender> <!-- aop日志输出-mms --> <appender name="log-all" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>%d{MM-dd HH:mm:ss.SSS}-[%t]-[%-5level]-[%logger{30}] - %msg%n</pattern> <charset>utf8</charset> </encoder> <file>./${LOG_HOME}/log-all.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/log-all-%d{yyyy-MM-dd}-%i.log.zip</fileNamePattern> <maxHistory>30</maxHistory> <totalSizeCap>6GB</totalSizeCap> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <!--输出到error-all--> <appender name="error-all" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/error-all.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/error-all-%d{yyyy-MM-dd}-%i.log.zip</fileNamePattern> <MaxHistory>30</MaxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} -[%t]- [ %-5level ] - %msg%n</pattern> </layout> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- 基础日志输出级别 --> <root level="info"> <appender-ref ref="CONSOLE"/> <appender-ref ref="log-all"/> <appender-ref ref="error-all"/> </root> </configuration>
7.操作的数据库实体对象SysUser.java如下
注意为了后面编写代码方便,开启了链式编程,即增加了注解:@Accessors(chain = true),表示开启链式编程默认是关闭的;
package com.ldp.entity; import lombok.Data; import lombok.experimental.Accessors; import java.util.Date; /** * @author 姿势帝-博客园 * @address https://www.cnblogs.com/newAndHui/ * @WeChat 851298348 * @create 11/06 8:55 * @description */ @Data @Accessors(chain = true) public class SysUser { private Integer id; private Integer version; private Integer age; private Integer gender; private String name; private String position; private String account; private String password; private String status; private String type; private Date createTime; private Date updateTime; }
8.SysUserMapper.java接口,主要是继承了BaseMapper<SysUser>,全靠它自动帮我们完成了单表的CRUD
package com.ldp.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.ldp.entity.SysUser; /** * @author 姿势帝-博客园 * @address https://www.cnblogs.com/newAndHui/ * @WeChat 851298348 * @create 11/06 8:54 * @description */ public interface SysUserMapper extends BaseMapper<SysUser> { }
9.启动类文件如下,主要是启动类上加了扫描mapper接口的配置
@MapperScan({"com.ldp.mapper"})
package com.ldp; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan({"com.ldp.mapper"}) public class MpDemoApplication { /** * maven仓库地址 * https://mvnrepository.com/ */ public static void main(String[] args) { SpringApplication.run(MpDemoApplication.class, args); } }
到此基本环境就准备完了,别看我什么代码都没写,只是弄了一个结构,
但是我告诉你SysUser表的所有增删改查都已经实现了,
下面大家可以看一下测试怎么使用SysUserMapper完成增删改查的,草鸡简单额
3.基本crud实现
什么代码都不用写,基本增删改查就已经有了
测试代码如下:
package com.ldp.demo01; import com.ldp.entity.SysUser; import com.ldp.mapper.SysUserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; /** * @author 姿势帝-博客园 * @address https://www.cnblogs.com/newAndHui/ * @WeChat 851298348 * @create 11/06 9:43 * @description mybatis-plus 快速入门使用基本的CRUD */ @RunWith(SpringRunner.class) @SpringBootTest public class BaseCrudTest { @Autowired private SysUserMapper sysUserMapper; /** * 增加 * <p> * ==> Preparing: INSERT INTO sys_user ( age, name ) VALUES ( ?, ? ) * ==> Parameters: 18(Integer), 李东平(String) */ @Test public void test() { int row = sysUserMapper.insert(new SysUser().setName("李东平").setAge(18)); System.out.println("受影响行数:" + row); } /** * 根据id删除 * <p> * ==> Preparing: DELETE FROM sys_user WHERE id=? * ==> Parameters: 18(Integer) */ @Test public void deleteById() { int row = sysUserMapper.deleteById(18); System.out.println("受影响行数:" + row); } /** * 根据id修改 * <p> * ==> Preparing: UPDATE sys_user SET name=? WHERE id=? * ==> Parameters: 李东平->ldp(String), 20(Integer) * <== Updates: 1 */ @Test public void updateById() { int row = sysUserMapper.updateById(new SysUser().setName("李东平->ldp").setId(20)); System.out.println("受影响行数:" + row); } /** * 根据id查询 * * ==> Preparing: SELECT id,version,age,gender,name,position,account,password,status,type,create_time,update_time FROM sys_user WHERE id=? * ==> Parameters: 20(Integer) */ @Test public void selectById() { SysUser sysUser = sysUserMapper.selectById(20); System.out.println("sysUser:" + sysUser); } /** * 查询所有 * <p> * ==> Preparing: SELECT id,version,age,gender,name,position,account,password,status,type,create_time,update_time FROM sys_user * ==> Parameters: */ @Test public void selectList() { List<SysUser> users = sysUserMapper.selectList(null); System.out.println(users); } }
mybatis-plus系统化学习教程:https://www.cnblogs.com/newAndHui/p/14141950.html