SpringBoot和MybatisPlus實(shí)現(xiàn)通用Controller示例
基于SpringBoot和MybatisPlus實(shí)現(xiàn)通用Controller,只需要?jiǎng)?chuàng)建實(shí)體類(lèi)和mapper接口,單表增刪改查接口就已經(jīng)實(shí)現(xiàn),提升開(kāi)發(fā)效率
1.定義通用controller
package com.xian.controller;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xian.common.alias.*;
import com.xian.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
@RestController
@RequestMapping("/api/v1/data")
public class BaseController<T extends Serializable> {
@Autowired
private ApplicationContext applicationContext;
private T entity;
// 使用泛型和IService來(lái)處理通用CRUD操作
protected <S extends BaseMapper<T>> S getMapper(String entityName) throws Exception {
String serviceName = entityName + "Mapper"; // 假設(shè)服務(wù)名與實(shí)體名相同
return (S) applicationContext.getBean(serviceName);
}
@GetMapping("/{entityName}/get/{id}")
public Result get(@PathVariable String entityName, @PathVariable Long id) throws Exception {
BaseMapper<T> mapper = getMapper(entityName);
return Result.success(mapper.selectById(id));
}
@GetMapping("/{entityName}/all")
public Result get(@PathVariable String entityName) throws Exception {
BaseMapper<T> mapper = getMapper(entityName);
return Result.success(mapper.selectList(new QueryWrapper<>()));
}
@PostMapping("/{entityName}/insert")
public Result insert(@PathVariable String entityName,@RequestBody T entity) throws Exception {
BaseMapper<T> baseMapper = getMapper(entityName);
ValidateService<T> validateService = new ValidateServiceImpl<>();
validateService.validate(entity,baseMapper);
baseMapper.insert(entity);
return Result.success();
}
@PutMapping("/{entityName}/update")
public Result update(@PathVariable String entityName,@RequestBody T entity) throws Exception {
BaseMapper<T> baseMapper = getMapper(entityName);
// 使用Spring注入驗(yàn)證服務(wù)
// 驗(yàn)證數(shù)據(jù)
ValidateService<T> validateService = new ValidateServiceImpl<>();
validateService.validate(entity, baseMapper);
baseMapper.updateById(entity);
return Result.success();
}
@PutMapping("/{entityName}/delete/{id}")
public Result update(@PathVariable String entityName,@PathVariable Long id) throws Exception {
BaseMapper<T> baseMapper = getMapper(entityName);
baseMapper.deleteById(id);
return Result.success();
}
@PutMapping("/{entityName}/deleteByIds")
public Result update(@PathVariable String entityName,@RequestBody Collection<Long> ids) throws Exception {
BaseMapper<T> baseMapper = getMapper(entityName);
baseMapper.deleteBatchIds(ids);
return Result.success();
}
// 可以添加其他通用的增刪改查方法...
@PostMapping("/{entityName}/list")
public Result update(@PathVariable String entityName, @RequestBody PageRequestVo pageRequest) throws Exception {
BaseMapper<T> baseMapper = getMapper(entityName);
System.out.println("pageRequest = " + pageRequest);
PageHelper.startPage(pageRequest.getPage(), pageRequest.getSize());
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
List<String> sort = pageRequest.getSorts();
if (sort!=null&& !sort.isEmpty()) {
sort.forEach(o -> {
if (o.endsWith("Asc")) {
queryWrapper.orderByAsc(o.replace("Asc", ""));
}else if (o.endsWith("Desc")) {
queryWrapper.orderByDesc(o.replace("Desc", ""));
}else {
queryWrapper.orderByAsc(o);
}
});
}
if (!MapUtil.isEmpty(pageRequest.getParams())){
// 處理查詢(xún)參數(shù)
pageRequest.getParams().forEach((field, values) -> {
if (values != null && !values.isEmpty()) {
if (field.endsWith("Like")) {
for (Object value : values) {
queryWrapper.like(field.replace("Like",""), value);
}
}else if (field.endsWith("Is")){
for (Object value : values) {
queryWrapper.eq(field.replace("Like",""), value);
}
}else if (field.endsWith("Between")){
queryWrapper.between(field.replace("Between",""), values.get(0), values.get(1));
}else if (field.endsWith("IsNull")){
queryWrapper.isNull(field.replace("IsNull",""));
}else if (field.endsWith("IsNotNull")){
queryWrapper.isNotNull(field.replace("IsNotNull",""));
}else if (field.endsWith("NotIn")){
queryWrapper.notIn(field.replace("NotIn",""), values);
}else if (field.endsWith("In")){
queryWrapper.in(field.replace("In",""), values);
}else if (field.endsWith("Gt")){
queryWrapper.gt(field.replace("Gt",""), values.get(0));
}else if (field.endsWith("Ge")){
queryWrapper.ge(field.replace("Ge",""), values.get(0));
}else if (field.endsWith("Lt")){
queryWrapper.lt(field.replace("Lt",""), values.get(0));
}else if (field.endsWith("Le")){
queryWrapper.le(field.replace("Le",""), values.get(0));
}else if (field.endsWith("Eq")){
for (Object value : values) {
queryWrapper.eq(field.replace("Eq",""), value);
}
}else if (field.endsWith("Ne")){
queryWrapper.ne(field.replace("Ne",""), values.get(0));
}else if (field.endsWith("NotBetween")){
queryWrapper.notBetween(field.replace("NotBetween",""), values.get(0), values.get(1));
}else {
for (Object value : values) {
queryWrapper.eq(field, value);
}
}
}
});
}
return Result.success(PageInfo.of(baseMapper.selectList(queryWrapper)));
}
}
2.創(chuàng)建業(yè)務(wù)實(shí)體和mapper接口,
@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User extends Account {
@TableId(type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String name;
private String avatar;
private String role;
private String sex;
private String phone;
private String email;
private String info;
private String birth;
@TableField(exist = false)
private Integer blogCount;
@TableField(exist = false)
private Integer likesCount;
@TableField(exist = false)
private Integer collectCount;
}mapper接口:
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
postman測(cè)試

到此這篇關(guān)于SpringBoot和MybatisPlus實(shí)現(xiàn)通用Controller的文章就介紹到這了,更多相關(guān)SpringBoot MybatisPlus 通用Controller內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot如何實(shí)現(xiàn)調(diào)用controller和Service層方法
- springboot中的controller參數(shù)映射問(wèn)題小結(jié)
- springboot中Controller內(nèi)文件上傳到本地及阿里云操作方法
- springboot如何通過(guò)controller層實(shí)現(xiàn)頁(yè)面切換
- springboot Controller直接返回String類(lèi)型帶來(lái)的亂碼問(wèn)題及解決
- SpringBoot之controller參數(shù)校驗(yàn)詳解
- springboot中@RestController注解實(shí)現(xiàn)
- SpringBoot通過(guò)注解監(jiān)測(cè)Controller接口的代碼示例
- springboot controller參數(shù)注入方式
- SpringBoot中@RestControllerAdvice @ExceptionHandler異常統(tǒng)一處理類(lèi)失效原因分析
相關(guān)文章
Spring事務(wù)管理中@Transactional失效的8個(gè)常見(jiàn)場(chǎng)景與解決方案
在實(shí)際開(kāi)發(fā)中,你是否遇到過(guò)明明在方法上添加了@Transactional注解,但事務(wù)卻沒(méi)有按預(yù)期工作,本文將深入剖析Spring事務(wù)管理中常見(jiàn)的8個(gè)陷阱,幫助你徹底解決這些問(wèn)題2025-11-11
java靈活使用mysql中json類(lèi)型字段存儲(chǔ)數(shù)據(jù)詳解
在數(shù)據(jù)庫(kù)設(shè)計(jì)中,面對(duì)一對(duì)多的關(guān)系,如訂單和商品,可以考慮使用單表存儲(chǔ)而非傳統(tǒng)的分表方式,這篇文章主要介紹了java靈活使用mysql中json類(lèi)型字段存儲(chǔ)數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2024-09-09
Java中LinkedHashSet的實(shí)現(xiàn)原理詳解
這篇文章主要介紹了Java中LinkedHasSet的實(shí)現(xiàn)原理詳解,LinkedHashSet?是具有可預(yù)知迭代順序的?Set?接口的哈希表和鏈接列表實(shí)現(xiàn),此實(shí)現(xiàn)與HashSet?的不同之處在于,后者維護(hù)著一個(gè)運(yùn)行于所有條目的雙重鏈接列表,需要的朋友可以參考下2023-09-09
springboot使用filter獲取自定義請(qǐng)求頭的實(shí)現(xiàn)代碼
這篇文章主要介紹了springboot使用filter獲取自定義請(qǐng)求頭的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
IDEA導(dǎo)入Eclipse項(xiàng)目全過(guò)程
這篇文章介紹了如何將Eclipse項(xiàng)目導(dǎo)入到IntelliJ IDEA,并詳細(xì)步驟如下:新建一個(gè)文件夾,用IntelliJ IDEA打開(kāi),將項(xiàng)目導(dǎo)入,等待編譯完成,配置項(xiàng)目環(huán)境和結(jié)構(gòu),注意文件夾名稱(chēng)可能不同,配置Tomcat,重新編譯項(xiàng)目并啟動(dòng)2025-11-11
springboot+dynamicDataSource動(dòng)態(tài)添加切換數(shù)據(jù)源方式
這篇文章主要介紹了springboot+dynamicDataSource動(dòng)態(tài)添加切換數(shù)據(jù)源方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot路徑映射實(shí)現(xiàn)過(guò)程圖解
這篇文章主要介紹了SpringBoot路徑映射實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
spring注解之@Valid和@Validated的區(qū)分總結(jié)
@Validated和@Valid在基本驗(yàn)證功能上沒(méi)有太多區(qū)別,但在分組、注解地方、嵌套驗(yàn)證等功能上有所不同,下面這篇文章主要給大家介紹了關(guān)于spring注解之@Valid和@Validated區(qū)分的相關(guān)資料,需要的朋友可以參考下2022-03-03
Java阻塞隊(duì)列必看類(lèi):BlockingQueue快速了解大體框架和實(shí)現(xiàn)思路
這篇文章主要介紹了Java阻塞隊(duì)列必看類(lèi):BlockingQueue快速了解大體框架和實(shí)現(xiàn)思路,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Spring?Boot基于?JWT?優(yōu)化?Spring?Security?無(wú)狀態(tài)登錄實(shí)戰(zhàn)指南
本文介紹如何使用JWT優(yōu)化SpringSecurity實(shí)現(xiàn)無(wú)狀態(tài)登錄,提高接口安全性,并通過(guò)實(shí)際操作步驟展示了如何配置JWT參數(shù)、實(shí)現(xiàn)JWT登錄接口、認(rèn)證過(guò)濾器等,感興趣的朋友跟隨小編一起看看吧2025-11-11

