Mybatis-Plus3.0入門手冊


Mybatis-Plus3.0入門手冊

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM