Mybatis-Plus3.0入门手册

 
ref: https://blog.csdn.net/moshowgame/article/details/81008485

Mybatis-Plus简介

Mybatis-Plus 是一款 Mybatis 动态 SQL 自动注入 Mybatis 增删改查 CRUD 操作中间件, 减少你的开发周期优化动态维护 XML 实体字段,无入侵全方位 ORM 辅助层让您拥有更多时间陪家人。

Mybatis-Plus特性

  • 无侵入:Mybatis-Plus 在 Mybatis 的基础上进行扩展,只做增强不做改变,引入 Mybatis-Plus 不会对您现有的 Mybatis 构架产生任何影响,而且 MP 支持所有 Mybatis 原生的特性
  • 依赖少:仅仅依赖 Mybatis 以及 Mybatis-Spring
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 预防Sql注入:内置 Sql 注入剥离器,有效预防Sql注入攻击
  • 通用CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 多种主键策略:支持多达4种主键策略(内含分布式唯一ID生成器),可自由配置,完美解决主键问题
  • 支持热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
  • 支持ActiveRecord:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作
  • 支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用(P.S. 比 Mybatis 官方的 Generator 更加强大!)
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 支持关键词自动转义:支持数据库关键词(order、key……)自动转义,还可自定义关键词
  • 内置分页插件:基于 Mybatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通List查询
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能有效解决慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,预防误操作

官网

http://mp.baomidou.com/ 
https://github.com/baomidou/mybatis-plus

为什么有这个入门手册

目前最新版本:3.0 alpha/beta,升级 JDK 8 + 优化性能 Wrapper 支持 lambda 语法等等, Wrapper 也更改为 QueryWrapper和UpdateWrapper,网上的攻略已经不行了,这里提供一个新版本的入门采坑手册,并附上spring-cloud-study-mybatisplus开源学习项目。那么教程开始了。

maven的pom.xml配置

    <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0-beta</version>
</dependency>
<!-- mybatis-plus begin -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0-beta</version>
</dependency>
<!-- mybatis-plus end -->
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

application.yml应用配置

官方给的配置,有报错,集中报错在IDGenerator那边,于是暂时屏蔽了,mysql是不需要的,如果用在oracle上应该是需要配置,等官方更新demo配置。

server:
port: 3333
servlet:
context-path: /mybatisplus
tomcat:
remote-ip-header: x-forward-for
uri-encoding: UTF-8
max-threads: 10
background-processor-delay: 30
spring:
http:
encoding:
force: true
charset: UTF-8
application:
name: spring-cloud-study-mybatisplus
freemarker:
request-context-attribute: req
#prefix: /templates/
suffix: .html
content-type: text/html
enabled: true
cache: false
charset: UTF-8
allow-request-override: false
expose-request-attributes: true
expose-session-attributes: true
expose-spring-macro-helpers: true
#template-loader-path: classpath:/templates/
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
driver-class-name: com.mysql.jdbc.Driver
platform: mysql
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
filters: stat,wall,log4j
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8888/eureka/
instance:
ip-address: ture
mybatis-plus:
# 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml
mapper-locations: classpath:/com/softdev/system/demo/entity/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.softdev.system.*.entity
global-config:
db-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: UUID
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: NOT_EMPTY
#驼峰下划线转换
table-underline: true
#mp2.3+ 全局表前缀 mp_
#table-prefix: mp_
#刷新mapper 调试神器
#refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
# Sequence序列接口实现类配置
#key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
#逻辑删除配置(下面3个配置)
logic-delete-value: 1
logic-not-delete-value: 0
#sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
configuration:
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
map-underscore-to-camel-case: true
cache-enabled: false
#配置JdbcTypeForNull, oracle数据库必须配置
jdbc-type-for-null: 'null'

entity和mapper

Mapper只需要extends BaseMapper<T>就可以完美实现增删改查等一系列操作,非常方便

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User>{

} 

这里Entity省略setter和getter方法,可以用lombok的@Data代替

@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L; private int id; private String userId; private String userName; private String passWord; private String name; private String tell; private int status;
}

Controller控制器

这里随便写个init方法和find方法,init就不用说了,初始化一些数据进去,find使用了QueryWrapper构造器,很方便。

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper; @GetMapping("/init")
public ApiReturnObject init(){
List<User> userList=new ArrayList<User>();
for (int i = 0; i < 10; i++) {
int n=RandomUtil.randomInt(10000,99999)+i;
User user=new User();
user.setId(n);
user.setName(n+"");
user.setPassWord(n+"");
user.setStatus(1);
user.setUserId(n+"");
user.setUserName(n+"");
userMapper.insert(user);
userList.add(user);
user=null;
}
return ApiReturnUtil.success(userList);
} @GetMapping("/find")
public ApiReturnObject find(){
IPage<User> userList=userMapper.selectPage(
new Page<User>(1, 10),
new QueryWrapper<User>().like("name","1")
);
return ApiReturnUtil.success(userList.getRecords());
}
}

Postman测试

访问数据初始化 http://127.0.0.1:1111/mybatisplus/user/init

{
"errorCode": "00",
"errorMessage": "success",
"returnObject": [
{
"id": 52585,
"name": "52585",
"passWord": "52585",
"status": 1,
"userId": "52585",
"userName": "52585"
},
{
"id": 33432,
"name": "33432",
"passWord": "33432",
"status": 1,
"userId": "33432",
"userName": "33432"
}
。。。这里省略其他的
]
}

访问构造器查询 http://127.0.0.1:3333/mybatisplus/user/find

{
"errorCode": "00",
"errorMessage": "success",
"returnObject": [
{
"id": 41618,
"name": "41618",
"passWord": "41618",
"status": 1,
"userId": "41618",
"userName": "41618"
},
{
"id": 17804,
"name": "17804",
"passWord": "17804",
"status": 1,
"userId": "17804",
"userName": "17804"
}
。。。省略其他包含1的
]
}

QueryWrapper条件参数说明

查询方式 说明
setSqlSelect 设置 SELECT 查询字段
where WHERE 语句,拼接 + WHERE 条件
and AND 语句,拼接 + AND 字段=值
andNew(已失效) AND 语句,拼接 + AND (字段=值)
or OR 语句,拼接 + OR 字段=值
orNew(已失效) OR 语句,拼接 + OR (字段=值)
eq 等于=
allEq 基于 map 内容等于=
ne 不等于<>
gt 大于>
ge 大于等于>=
lt 小于<
le 小于等于<=
like 模糊查询 LIKE
notLike 模糊查询 NOT LIKE
in IN 查询
notIn NOT IN 查询
isNull NULL 值查询
isNotNull IS NOT NULL
groupBy 分组 GROUP BY
having HAVING 关键词
orderBy 排序 ORDER BY
orderByAsc(有变化,中间有By) ASC 排序 ORDER BY
orderByDesc(有变化,中间有By) DESC 排序 ORDER BY
exists EXISTS 条件语句
notExists NOT EXISTS 条件语句
between BETWEEN 条件语句
notBetween NOT BETWEEN 条件语句
addFilter 自由拼接 SQL
last 拼接在最后,例如:last(“LIMIT 1”)

分页插件

已经在springboot注入mybatis的分页插件,直接使用Page参数

    IPage<User> userList=userMapper.selectPage(
new Page<User>(1, 10),
new QueryWrapper<User>().like("name","1")
);

项目源码

https://github.com/moshowgame/spring-cloud-study 
https://github.com/moshowgame/spring-cloud-study/tree/master/spring-cloud-study-mybatisplus

Mybatis-Plus3.0入门手册的更多相关文章

  1. mybatis plus3.1.0 热加载mapper

    今天又开始写业务代码了,每次修改SQL都要重启服务,实在是浪费时间. 想起之前研究过的<mybatis plus3.1.0 热加载mapper>,一直没有成功,今天静下心来分析了问题,终于 ...

  2. Node.js 入门手册:那些最流行的 Web 开发框架

    这篇文章与大家分享最流行的 Node.js Web 开发框架.Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用程序,编 ...

  3. DPDK2.1 linux上开发入门手册

    1引言 本文档主要包含INTEL DPDK安装和配置说明.目的是让用户快速的开发和运行程序.文档描述了如何在不深入细节的情况下在linux应用开发环境上编译和运行一个DPDK应用程序. 1.1文档总览 ...

  4. MyBatis(1)——快速入门

    MyBatis 简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...

  5. MyBean 框架入门手册<感谢[青铜]整理的如此细致和系统>

    MyBean 框架入门手册 2014/9/15 by lighttop 目 录 MyBean 框架学习笔记............................................... ...

  6. (转) MyBatis(1)——快速入门

    MyBatis 简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...

  7. Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建

    目录 Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建 0.项目准备 1.数据持久层Mybatis+MySQL 1.1 MySQL数据准备 1.2 Mybatis ...

  8. hadoop入门手册5:Hadoop【2.7.1】初级入门之命令:文件系统shell2

    问题导读 1.改变hdfs文件的权限,需要修改哪个配置文件?2.获取一个文件的或则目录的权限,哪个命令可以实现?3.哪个命令可以实现设置访问控制列表(ACL)的文件和目录? 接上篇:Hadoop[2. ...

  9. hadoop入门手册4:Hadoop【2.7.1】初级入门之命令:文件系统shell1

    问题导读1.Hadoop文件系统shell与Linux shell有哪些相似之处?2.如何改变文件所属组?3.如何改变hdfs的文件权限?4.如何查找hdfs文件,并且不区分大小写? 概述文件系统 ( ...

随机推荐

  1. git add -A /git add -u/git add .的用法

    git的指令详解 在git中有好多的指令,但是今天这几个指令就很容易忘记而且还容易混淆 git add -u <==> git add –update 提交所有被删除和修改的文件到数据暂存 ...

  2. 修改postfix smtp端口,防止公网扫描浪费你的服务器流量

    邮件服务器的默认发送邮件端口是25,一些ISP会封锁25端口防止垃圾邮件的发送,这样就导致不能使用Foxmail.outlook等邮件客户端发送邮件.修改默认smtp端口就可以解决这个问题.下面的方法 ...

  3. ThreadingTCPServer 如何设置端口重用

    一个典型的TCPServer的建立 #ThreadingTCPServer从ThreadingMixIn和TCPServer继承 #class ThreadingTCPServer(Threading ...

  4. MySQL性能管理及架构设计

    第1章 实例和故事 1-1 什么决定了电商双11大促的成败 老板可能会说:"是我们的英明决策和运筹帷幄". 运营和产品可能会说:"是由于我们的活动策划和产品设计" ...

  5. wcf 数值类型赋值不能的问题解决

    客户端给对象int类型赋值,服务端收到值为0 网上给出的方案 1.数值型字段+isrequired属性.能解决问题,但没有说明原因.数值型默认不赋值,不科学. 2.emitdefaultvalue.没 ...

  6. [蓝桥杯]ALGO-124.算法训练_数字三角形

    问题描述 (图3.1-1)示出了一个数字三角形. 请编一个程序计算从顶至底的某处的一条路 径,使该路径所经过的数字的总和最大. ●每一步可沿左斜线向下或右斜线向下走: ●<三角形行数≤: ●三角 ...

  7. [蓝桥杯]ALGO-79.算法训练_删除数组零元素

    从键盘读入n个整数放入数组中,编写函数CompactIntegers,删除数组中所有值为0的元素,其后元素向数组首端移动.注意,CompactIntegers函数需要接受数组及其元素个数作为参数,函数 ...

  8. C++进阶--结构体和类

    // 单纯从语言上来说,两者唯一的区别是,默认成员是公有还是私有 // 从使用习惯上 // 小的消极对象,包含公有数据,没有或仅有很少的基本的成员函数 -- 数据容器 struct Person_t ...

  9. PAT 乙级 1012 数字分类 (20) C++版

    1012. 数字分类 (20) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 给定一系列正整数,请按要求对数字进 ...

  10. 延时队列:Java中的DelayQueue

    Java中的DelayQueue位于java.util.concurrent包下,本质是由PriorityQueue和BlockingQueue实现的阻塞优先级队列. 放入队列的元素需要实现java. ...