SpringBoot整合Mybatis-plus的具體使用
一、mybatis-plus簡介:
Mybatis-Plus(簡稱MP)是一個 Mybatis 的增強工具,在 Mybatis 的基礎(chǔ)上只做增強不做改變,為簡化開發(fā)、提高效率而生。這是官方給的定義,關(guān)于mybatis-plus的更多介紹及特性,可以參考mybatis-plus官網(wǎng)。那么它是怎么增強的呢?其實就是它已經(jīng)封裝好了一些crud方法,我們不需要再寫xml了,直接調(diào)用這些方法就行,就類似于JPA。并且3.X系列支持lambda語法,讓我在寫條件構(gòu)造的時候少了很多的"魔法值",從代碼結(jié)構(gòu)上更簡潔了.
二、springboot整合mybatis-plus案例
pom.xml配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--springboot程序測試依賴,如果是自動創(chuàng)建項目默認(rèn)添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<!-- 包含spirng Mvc ,tomcat的包包含requestMapping restController 等注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<!-- mybatisPlus 核心庫 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>application.yml配置
server:
port: 10100 # 配置啟動端口號
mybatis:
config-location: classpath:mybatis.cfg.xml # mybatis主配置文件所在路徑
type-aliases-package: com.demo.drools.entity # 定義所有操作類的別名所在包
mapper-locations: # 所有的mapper映射文件
- classpath:mapper/*.xml
spring: #springboot的配置
datasource: #定義數(shù)據(jù)源
#127.0.0.1為本機測試的ip,3306是mysql的端口號。serverTimezone是定義時區(qū),照抄就好,mysql高版本需要定義這些東西
#useSSL也是某些高版本mysql需要問有沒有用SSL連接
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useSSL=FALSE
username: root #數(shù)據(jù)庫用戶名,root為管理員
password: 123456 #該數(shù)據(jù)庫用戶的密碼
# 使用druid數(shù)據(jù)源
type: com.alibaba.druid.pool.DruidDataSource
# mybatis-plus相關(guān)配置
mybatis-plus:
# xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應(yīng)的 XML 文件位置)
mapper-locations: classpath:mapper/*.xml
# 以下配置均有默認(rèn)值,可以不設(shè)置
global-config:
db-config:
#主鍵類型 AUTO:"數(shù)據(jù)庫ID自增" INPUT:"用戶輸入ID",ID_WORKER:"全局唯一ID (數(shù)字類型唯一ID)", UUID:"全局唯一ID UUID";
id-type: auto
#字段策略 IGNORED:"忽略判斷" NOT_NULL:"非 NULL 判斷") NOT_EMPTY:"非空判斷"
field-strategy: NOT_EMPTY
#數(shù)據(jù)庫類型
db-type: MYSQL
configuration:
# 是否開啟自動駝峰命名規(guī)則映射:從數(shù)據(jù)庫列名到Java屬性駝峰命名的類似映射
map-underscore-to-camel-case: true
# 如果查詢結(jié)果中包含空值的列,則 MyBatis 在映射的時候,不會映射這個字段
call-setters-on-nulls: true
# 這個配置會將執(zhí)行的sql打印出來,在開發(fā)或測試的時候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl用戶信息實體
package com.demo.drools.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* TODO your comment
*
* @author Yujiaqi
* @date 2020/12/2 19:14
*/
@Data
@TableName("user_info")//@TableName中的值對應(yīng)著表名
public class UserInfoEntity {
/**
* 主鍵
* @TableId中可以決定主鍵的類型,不寫會采取默認(rèn)值,默認(rèn)值可以在yml中配置
* AUTO: 數(shù)據(jù)庫ID自增
* INPUT: 用戶輸入ID
* ID_WORKER: 全局唯一ID,Long類型的主鍵
* ID_WORKER_STR: 字符串全局唯一ID
* UUID: 全局唯一ID,UUID類型的主鍵
* NONE: 該類型為未設(shè)置主鍵類型
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private Integer age;
/**
* 技能
*/
private String skill;
/**
* 評價
*/
private String evaluate;
/**
* 分?jǐn)?shù)
*/
private Long fraction;
}config類
package com.demo.drools.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
/**
* TODO your comment
*
* @author Yujiaqi
* @date 2020/12/2 19:14
*/
public class MybatisPlusConfig {
/**
* mybatis-plus SQL執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}spring boot啟動類
package com.demo.drools;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author 于嘉琪
*/
@SpringBootApplication
//@MapperScan和dao層添加@Mapper注解意思一樣
@MapperScan(basePackages = "com.demo.drools.dao")
public class DroolsApplication {
public static void main(String[] args) {
SpringApplication.run(DroolsApplication.class, args);
}
}dao層
package com.demo.drools.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.drools.entity.UserInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 用戶信息DAO
*
* @author Yujiaqi
* @date 2020/12/2 19:16
*/
@Mapper
public interface UserInfoDao extends BaseMapper<UserInfoEntity> {
}service層
package com.demo.drools.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.demo.drools.entity.UserInfoEntity;
/**
* TODO your comment
*
* @author Yujiaqi
* @date 2020/12/2 19:17
*/
public interface UserInfoService extends IService<UserInfoEntity> {
}serviceImpl實現(xiàn)類層
package com.demo.drools.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.drools.dao.UserInfoDao;
import com.demo.drools.entity.UserInfoEntity;
import com.demo.drools.service.UserInfoService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* TODO your comment
*
* @author Yujiaqi
* @date 2020/12/2 19:18
*/
@Service
public class UserInfoSerivceImpl extends ServiceImpl<UserInfoDao, UserInfoEntity> implements UserInfoService {
}controller控制層
package com.demo.drools.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.drools.entity.UserInfoEntity;
import com.demo.drools.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* TODO your comment
*
* @author Yujiaqi
* @date 2020/12/2 19:20
*/
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
/**
* 根據(jù)ID獲取用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:34
* @Param userId 用戶ID
* @Return UserInfoEntity 用戶實體
*/
@RequestMapping("/getInfo")
public UserInfoEntity getInfo(String userId){
UserInfoEntity userInfoEntity = userInfoService.getById(userId);
return userInfoEntity;
}
/**
* 查詢?nèi)啃畔?
* @Author Sans
* @CreateTime 2019/6/8 16:35
* @Param userId 用戶ID
* @Return List<UserInfoEntity> 用戶實體集合
*/
@RequestMapping("/getList")
public List<UserInfoEntity> getList(){
List<UserInfoEntity> userInfoEntityList = userInfoService.list();
return userInfoEntityList;
}
/**
* 分頁查詢?nèi)繑?shù)據(jù)
* @Author Sans
* @CreateTime 2019/6/8 16:37
* @Return IPage<UserInfoEntity> 分頁數(shù)據(jù)
*/
@RequestMapping("/getInfoListPage")
public IPage<UserInfoEntity> getInfoListPage(){
//需要在Config配置類中配置分頁插件
IPage<UserInfoEntity> page = new Page<>();
page.setCurrent(5); //當(dāng)前頁
page.setSize(1); //每頁條數(shù)
page = userInfoService.page(page);
return page;
}
/**
* 根據(jù)指定字段查詢用戶信息集合
* @Author Sans
* @CreateTime 2019/6/8 16:39
* @Return Collection<UserInfoEntity> 用戶實體集合
*/
@RequestMapping("/getListMap")
public Collection<UserInfoEntity> getListMap(){
Map<String,Object> map = new HashMap<>();
//kay是字段名 value是字段值
map.put("age",20);
Collection<UserInfoEntity> userInfoEntityList = userInfoService.listByMap(map);
return userInfoEntityList;
}
/**
* 新增用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:40
*/
@RequestMapping("/saveInfo")
public void saveInfo(){
UserInfoEntity userInfoEntity = new UserInfoEntity();
userInfoEntity.setName("小龍");
userInfoEntity.setSkill("JAVA");
userInfoEntity.setAge(18);
userInfoEntity.setFraction(59L);
userInfoEntity.setEvaluate("該學(xué)生是一個在改BUG的碼農(nóng)");
userInfoService.save(userInfoEntity);
}
/**
* 批量新增用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:42
*/
@RequestMapping("/saveInfoList")
public void saveInfoList(){
//創(chuàng)建對象
UserInfoEntity sans = new UserInfoEntity();
sans.setName("Sans");
sans.setSkill("睡覺");
sans.setAge(18);
sans.setFraction(60L);
sans.setEvaluate("Sans是一個愛睡覺,并且身材較矮骨骼巨大的骷髏小胖子");
UserInfoEntity papyrus = new UserInfoEntity();
papyrus.setName("papyrus");
papyrus.setSkill("JAVA");
papyrus.setAge(18);
papyrus.setFraction(58L);
papyrus.setEvaluate("Papyrus是一個講話大聲、個性張揚的骷髏,給人自信、有魅力的骷髏小瘦子");
//批量保存
List<UserInfoEntity> list =new ArrayList<>();
list.add(sans);
list.add(papyrus);
userInfoService.saveBatch(list);
}
/**
* 更新用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:47
*/
@RequestMapping("/updateInfo")
public void updateInfo(){
//根據(jù)實體中的ID去更新,其他字段如果值為null則不會更新該字段,參考yml配置文件
UserInfoEntity userInfoEntity = new UserInfoEntity();
userInfoEntity.setId(1L);
userInfoEntity.setAge(19);
userInfoService.updateById(userInfoEntity);
}
/**
* 新增或者更新用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:50
*/
@RequestMapping("/saveOrUpdateInfo")
public void saveOrUpdate(){
//傳入的實體類userInfoEntity中ID為null就會新增(ID自增)
//實體類ID值存在,如果數(shù)據(jù)庫存在ID就會更新,如果不存在就會新增
UserInfoEntity userInfoEntity = new UserInfoEntity();
userInfoEntity.setId(1L);
userInfoEntity.setAge(20);
userInfoService.saveOrUpdate(userInfoEntity);
}
/**
* 根據(jù)ID刪除用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:52
*/
@RequestMapping("/deleteInfo")
public void deleteInfo(String userId){
userInfoService.removeById(userId);
}
/**
* 根據(jù)ID批量刪除用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:55
*/
@RequestMapping("/deleteInfoList")
public void deleteInfoList(){
List<String> userIdlist = new ArrayList<>();
userIdlist.add("12");
userIdlist.add("13");
userInfoService.removeByIds(userIdlist);
}
/**
* 根據(jù)指定字段刪除用戶信息
* @Author Sans
* @CreateTime 2019/6/8 16:57
*/
@RequestMapping("/deleteInfoMap")
public void deleteInfoMap(){
//kay是字段名 value是字段值
Map<String,Object> map = new HashMap<>();
map.put("skill","刪除");
map.put("fraction",10L);
userInfoService.removeByMap(map);
}
}controller層用到lambda語法
package com.demo.drools.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.drools.entity.UserInfoEntity;
import com.demo.drools.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* TODO your comment
*
* @author Yujiaqi
* @date 2020/12/2 19:28
*/
public class UserInfoPlusController {
@Autowired
private UserInfoService userInfoService;
/**
* MP擴展演示
* @Author Sans
* @CreateTime 2019/6/8 16:37
* @Return Map<String,Object> 返回數(shù)據(jù)
*/
@RequestMapping("/getInfoListPlus")
public Map<String,Object> getInfoListPage(){
//初始化返回類
Map<String,Object> result = new HashMap<>();
//查詢年齡等于18歲的學(xué)生
//等價SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE age = 18
QueryWrapper<UserInfoEntity> queryWrapper1 = new QueryWrapper<>();
queryWrapper1.lambda().eq(UserInfoEntity::getAge,18);
List<UserInfoEntity> userInfoEntityList1 = userInfoService.list(queryWrapper1);
result.put("studentAge18",userInfoEntityList1);
//查詢年齡大于5歲的學(xué)生且小于等于18歲的學(xué)生
//等價SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE age > 5 AND age <= 18
QueryWrapper<UserInfoEntity> queryWrapper2 = new QueryWrapper<>();
queryWrapper2.lambda().gt(UserInfoEntity::getAge,5);
queryWrapper2.lambda().le(UserInfoEntity::getAge,18);
List<UserInfoEntity> userInfoEntityList2 = userInfoService.list(queryWrapper2);
result.put("studentAge5",userInfoEntityList2);
//模糊查詢技能字段帶有"畫"的數(shù)據(jù),并按照年齡降序
//等價SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE skill LIKE '%畫%' ORDER BY age DESC
QueryWrapper<UserInfoEntity> queryWrapper3 = new QueryWrapper<>();
queryWrapper3.lambda().like(UserInfoEntity::getSkill,"畫");
queryWrapper3.lambda().orderByDesc(UserInfoEntity::getAge);
List<UserInfoEntity> userInfoEntityList3 = userInfoService.list(queryWrapper3);
result.put("studentAgeSkill",userInfoEntityList3);
//模糊查詢名字帶有"小"或者年齡大于18的學(xué)生
//等價SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE name LIKE '%小%' OR age > 18
QueryWrapper<UserInfoEntity> queryWrapper4 = new QueryWrapper<>();
queryWrapper4.lambda().like(UserInfoEntity::getName,"小");
queryWrapper4.lambda().or().gt(UserInfoEntity::getAge,18);
List<UserInfoEntity> userInfoEntityList4 = userInfoService.list(queryWrapper4);
result.put("studentOr",userInfoEntityList4);
//查詢評價不為null的學(xué)生,并且分頁
//等價SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE evaluate IS NOT NULL LIMIT 0,5
IPage<UserInfoEntity> page = new Page<>();
page.setCurrent(1);
page.setSize(5);
QueryWrapper<UserInfoEntity> queryWrapper5 = new QueryWrapper<>();
queryWrapper5.lambda().isNotNull(UserInfoEntity::getEvaluate);
page = userInfoService.page(page,queryWrapper5);
result.put("studentPage",page);
return result;
}
}以上就是mybatis-plus的小案例,mybatis-plus它像我之前使用的spring data jpa框架不用寫sql語句,就可以實現(xiàn)簡單的增刪改查、批量操作、分頁mybatis-plus功能還是比較強大,能減少我們寫很多代碼,我個人還是比較喜歡用這個mybatis-plus的
mybatis-plus只是mybatis的增強版,它不影響mybatis的使用,我們可以寫我們自定的方法以及sql,接下來我們看一個小案例
dao層新增方法
/**
* 查詢大于該分?jǐn)?shù)的學(xué)生
* @Author Sans
* @CreateTime 2019/6/9 14:28
* @Param page 分頁參數(shù)
* @Param fraction 分?jǐn)?shù)
* @Return IPage<UserInfoEntity> 分頁數(shù)據(jù)
*/
IPage<UserInfoEntity> selectUserInfoByGtFraction(
@Param(value = "page") IPage<UserInfoEntity> page,
@Param(value = "fraction")Long fraction);service新增方法
/**
* 查詢大于該分?jǐn)?shù)的學(xué)生
* @Author Sans
* @CreateTime 2019/6/9 14:27
* @Param page 分頁參數(shù)
* @Param fraction 分?jǐn)?shù)
* @Return IPage<UserInfoEntity> 分頁數(shù)據(jù)
*/
IPage<UserInfoEntity> selectUserInfoByGtFraction(IPage<UserInfoEntity> page,Long fraction);serviceImpl層新增方法
/**
* 查詢大于該分?jǐn)?shù)的學(xué)生
* @Author Sans
* @CreateTime 2019/6/9 14:27
* @Param page 分頁參數(shù)
* @Param fraction 分?jǐn)?shù)
* @Return IPage<UserInfoEntity> 分頁數(shù)據(jù)
*/
IPage<UserInfoEntity> selectUserInfoByGtFraction(IPage<UserInfoEntity> page,Long fraction);controller層新增方法
/**
* MP自定義SQL
* @Author Sans
* @CreateTime 2019/6/9 14:37
* @Return IPage<UserInfoEntity> 分頁數(shù)據(jù)
*/
@RequestMapping("/getInfoListSQL")
public IPage<UserInfoEntity> getInfoListSQL(){
//查詢大于60分以上的學(xué)生,并且分頁
IPage<UserInfoEntity> page = new Page<>();
page.setCurrent(1);
page.setSize(5);
page = userInfoService.selectUserInfoByGtFraction(page,60L);
return page;
}配置我們的mybatis的xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.demo.drools.dao.UserInfoDao">
<!-- Sans 2019/6/9 14:35 -->
<select id="selectUserInfoByGtFraction" resultType="com.demo.drools.entity.UserInfoEntity">
SELECT * FROM user_info WHERE fraction > #{fraction}
</select>
</mapper>以上配置就是我們的mybatis用法。
mybatis plus強大的條件構(gòu)造器queryWrapper、updateWrapper
1.QueryWrapper: Entity 對象封裝操作類
2.UpdateWrapper : Update 條件封裝,用于Entity對象更新操作
3.條件構(gòu)造器使用中的各個方法格式和說明

到此這篇關(guān)于SpringBoot整合Mybatis-plus的具體使用的文章就介紹到這了,更多相關(guān)SpringBoot整合Mybatis-plus 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java8新特性-lambda表達式入門學(xué)習(xí)心得
這篇文章主要介紹了java8新特性-lambda表達式入門學(xué)習(xí)心得,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
intellij idea修改maven配置時總是恢復(fù)默認(rèn)配置的解決方法idea版本(2020.2.x)
這篇文章主要介紹了intellij idea修改maven配置時總是恢復(fù)默認(rèn)配置的解決方法idea版本(2020.2.x),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
SpringBoot實現(xiàn)RabbitMQ監(jiān)聽消息的四種方式
本文主要介紹了SpringBoot實現(xiàn)RabbitMQ監(jiān)聽消息的四種方式,包括@RabbitListener,MessageListener接口,MessageListenerAdapter適配器,@RabbitHandler這幾種,感興趣的可以了解一下2024-05-05
Java 負(fù)載均衡的 5 種算法實現(xiàn)原理
這篇文章主要介紹Java 負(fù)載均衡的 5 種算法實現(xiàn)原理,負(fù)載均衡能夠平均分配客戶請求到服 務(wù)器陣列,借此提供快速獲取重要數(shù)據(jù),解決大量并發(fā)訪問服務(wù)問題,這種集群技術(shù)可以用最少的投資獲得接近于大型主機的性能。下面就來看看文章的具體內(nèi)容吧2021-10-10
Springboot項目使用Slf4j將日志保存到本地目錄的實現(xiàn)代碼
這篇文章主要介紹了Springboot項目使用Slf4j將日志保存到本地目錄的實現(xiàn)方法,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05

