springBoot整合mybatisplus全過程
1、mybatisPlus的簡(jiǎn)介
mybatisplus的文檔地址:簡(jiǎn)介 | MyBatis-Plus
MyBatis-Plus (opens new window)(簡(jiǎn)稱 MP)是一個(gè) MyBatis (opens new window)的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開發(fā)、提高效率而生。
2、特點(diǎn)
- 簡(jiǎn)化開發(fā):MyBatis Plus提供了一套簡(jiǎn)化的CRUD接口,使開發(fā)人員無需編寫大量的重復(fù)的SQL代碼。
- 高度可定制:MyBatis Plus支持自定義的SQL語句和映射,開發(fā)人員可以根據(jù)自己的需求進(jìn)行定制化開發(fā)。
- 強(qiáng)大的代碼生成器:MyBatis Plus提供了一套強(qiáng)大的代碼生成器,可以根據(jù)數(shù)據(jù)庫表自動(dòng)生成對(duì)應(yīng)的實(shí)體類、Mapper接口、Service接口和Controller等代碼,大大提高了開發(fā)效率。
- 支持多種數(shù)據(jù)庫:MyBatis Plus不僅支持MySQL、Oracle等常見數(shù)據(jù)庫,還支持一些非關(guān)系型數(shù)據(jù)庫,如MongoDB、Redis等。
3、開發(fā)步驟
(1)導(dǎo)入依賴
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- Druid依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>(2)編寫配置文件:(application.yml)
spring:
#數(shù)據(jù)源
datasource:
#1.JDBC
type: com.alibaba.druid.pool.DruidDataSource
#驅(qū)動(dòng)類
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/myschool?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
username: root
password: root
druid:
#2.連接池配置
#初始化連接池的連接數(shù)量 大小,最小,最大
initial-size: 20
min-idle: 20
max-active: 100
#配置獲取連接等待超時(shí)的時(shí)間
max-wait: 10000
#配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
min-evictable-idle-time-millis: 30000
# SQL 心跳指令
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
mybatis-plus:
configuration:
#與小駝峰命名相互轉(zhuǎn)換
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志配置
type-aliases-package: com.yzch.domain
#映射文件的配置
mapper-locations: classpath:/mapper/*Mapper.xml(3)編寫實(shí)體類
package com.yzch.domain;
import java.io.Serializable;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @TableName t_user
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName(value ="t_user")
public class TUser implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private Integer userId;
/**
*
*/
@ExcelProperty("用戶名")
private String userName;
/**
*
*/
@ExcelProperty("年齡")
private Integer userAge;
/**
*
*/
@ExcelProperty("性別")
private String userSex;
/**
*
*/
@ExcelProperty("收入")
private Integer userIncome;
/**
*
*/
@ExcelProperty("省份")
private String province;
/**
*
*/
@ExcelProperty("城市")
private String city;
/**
* 職業(yè)
*/
@ExcelProperty("職業(yè)")
private String userOccupation;
/**
* 是否有車,0是沒有,1是有
*/
@ExcelProperty("車")
private Integer userIsCar;
}
(4)編寫mapper文件
package com.yzch.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yzch.domain.TUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface TUserMapper extends BaseMapper<TUser> {
}
(5)編寫service文件
package com.yzch.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yzch.domain.TUser;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public interface TUserService extends IService<TUser> {
}
package com.yzch.service.impl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzch.domain.TUser;
import com.yzch.mapper.TUserMapper;
import com.yzch.service.TUserService;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {
}
注:到目前為止,我們就搭建完成了,可以試試寫代碼了。
(6)測(cè)試
@Autowired
private TUserService tUserService;
@Autowired
private TUserMapper tUserMapper;
public void test(){
List<TUser> tUsers = tUserService.list();
List<TUser> tUsers1 = tUserMapper.selectList(null);
}4、service層的相關(guān)方法
//新增
// 插入一條記錄(選擇字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量) batchSize 插入批次數(shù)
boolean saveBatch(Collection<T> entityList, int batchSize);
//新增或保存
// TableId 注解屬性值存在則更新記錄,否插入一條記錄
boolean saveOrUpdate(T entity);
// 根據(jù)updateWrapper嘗試更新,否繼續(xù)執(zhí)行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入 batchSize 插入批次數(shù)
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
//刪除
// 根據(jù) queryWrapper 設(shè)置的條件,刪除記錄
boolean remove(Wrapper<T> queryWrapper);
// 根據(jù) ID 刪除
boolean removeById(Serializable id);
// 根據(jù) columnMap 條件,刪除記錄
boolean removeByMap(Map<String, Object> columnMap);
// 刪除(根據(jù)ID 批量刪除)
boolean removeByIds(Collection<? extends Serializable> idList);
//更新
// 根據(jù) UpdateWrapper 條件,更新記錄 需要設(shè)置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根據(jù) whereWrapper 條件,更新記錄
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根據(jù) ID 選擇修改
boolean updateById(T entity);
// 根據(jù)ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根據(jù)ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
//查詢單條記錄
// 根據(jù) ID 查詢
T getById(Serializable id);
// 根據(jù) Wrapper,查詢一條記錄。結(jié)果集,如果是多個(gè)會(huì)拋出異常,隨機(jī)取一條加上限制條件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根據(jù) Wrapper,查詢一條記錄
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根據(jù) Wrapper,查詢一條記錄
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根據(jù) Wrapper,查詢一條記錄
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
//list
// 查詢所有
List<T> list();
// 查詢列表
List<T> list(Wrapper<T> queryWrapper);
// 查詢(根據(jù)ID 批量查詢)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查詢(根據(jù) columnMap 條件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查詢所有列表
List<Map<String, Object>> listMaps();
// 查詢列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查詢?nèi)坑涗?
List<Object> listObjs();
// 查詢?nèi)坑涗?
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根據(jù) Wrapper 條件,查詢?nèi)坑涗?
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根據(jù) Wrapper 條件,查詢?nèi)坑涗?
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
//page分頁查詢
// 無條件分頁查詢
IPage<T> page(IPage<T> page);
// 條件分頁查詢
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
// 無條件分頁查詢
IPage<Map<String, Object>> pageMaps(IPage<T> page);
// 條件分頁查詢
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
5、mapper層的相關(guān)方法
@Test
void selectUsers(){
List<User> list = userMapper.selectList(null);
list.forEach(System.out::print);
}
@Test
void insertUser(){
User u1=new User();
u1.setName("郭小嘉六號(hào)");
u1.setEmail("877224@qq.com");
u1.setAge(88);
int insert = userMapper.insert(u1);
System.out.println(insert);
}
@Test
void updateUser(){
User u1=new User();
u1.setId("100");
u1.setName("張三");
u1.setEmail("877224@qq.com");
u1.setAge(20);
userMapper.updateById(u1);
}
//執(zhí)行此方法的時(shí)候,需要在實(shí)體類的Id屬性上添加@TableId(value = "user_id")注解
@Test
void deleteUserById(){
QueryWrapper<User> wrapper=new QueryWrapper<User>();
wrapper.eq("id","100");
int delete = userMapper.delete(wrapper);
System.out.println(delete);
}
//批量刪除
Collection<Long> idList=new ArrayList<Long>();
idList.add(1L);
idList.add(2L);
idList.add(3L);
int i = userMapper.deleteBatchIds(idList);
System.out.println(i);6、自定義方法
//自定義方法
@Select("SELECT t1.*,t2.`address_name` FROM USER t1\n" +
" INNER JOIN address t2\n" +
" ON t1.`id`=t2.`id`")
List<UserAddressVO> selectUserAddress();總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- springboot整合mybatisplus,找不到bean解決方案
- SpringBoot基于MyBatisPlus實(shí)現(xiàn)公共字段自動(dòng)填充
- SpringBoot +MybatisPlus集成多數(shù)據(jù)源的使用案例
- SpringBoot+MybatisPlus+jdbc連接池配置多數(shù)據(jù)源的實(shí)現(xiàn)
- SpringBoot整合mybatisPlus實(shí)現(xiàn)批量插入并獲取ID詳解
- SpringBoot整合MybatisPlus的基本應(yīng)用指南
- springBoot中myBatisPlus的使用步驟及示例代碼
相關(guān)文章
解決JavaWeb-file.isDirectory()遇到的坑問題
JavaWeb開發(fā)中,使用`file.isDirectory()`判斷路徑是否為文件夾時(shí),需要特別注意:該方法只能判斷已存在的文件夾,若路徑不存在,無論其實(shí)際是否應(yīng)為文件夾,均會(huì)返回`false`,為了解決這個(gè)問題,可以采用正則表達(dá)式進(jìn)行判斷,但要求路徑字符串的結(jié)尾必須添加反斜杠(\)2025-02-02
Java序列化JSON丟失精度問題的解決方法(修復(fù)Long類型太長)
這篇文章主要給大家介紹了關(guān)于Java序列化JSON丟失精度問題的解決方法,修復(fù)Long類型太長的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03
使用java實(shí)現(xiàn)手機(jī)短信驗(yàn)證全過程
這篇文章主要介紹了使用java實(shí)現(xiàn)手機(jī)短信驗(yàn)證全過程,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
解決RestTemplate反序列化嵌套對(duì)象的問題
這篇文章主要介紹了解決RestTemplate反序列化嵌套對(duì)象的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
SpringBoot中驗(yàn)證用戶上傳的圖片資源的方法
這篇文章主要介紹了在SpringBoot中驗(yàn)證用戶上傳的圖片資源,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09
MyBatis limit分頁設(shè)置的實(shí)現(xiàn)
這篇文章主要介紹了MyBatis limit分頁設(shè)置的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

