最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot和MybatisPlus實現(xiàn)通用Controller示例

 更新時間:2025年03月14日 08:31:30   作者:呱呱123#  
本文主要介紹了SpringBoot和MybatisPlus實現(xiàn)通用Controller示例,只需創(chuàng)建實體類和mapper接口,就可以實現(xiàn)單表的增刪改查操作,具有一定的參考價值,感興趣的可以了解一下

基于SpringBoot和MybatisPlus實現(xiàn)通用Controller,只需要創(chuàng)建實體類和mapper接口,單表增刪改查接口就已經(jīng)實現(xiàn),提升開發(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來處理通用CRUD操作
    protected <S extends BaseMapper<T>> S getMapper(String entityName) throws Exception {
        String serviceName = entityName + "Mapper"; // 假設(shè)服務(wù)名與實體名相同
        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注入驗證服務(wù)
        // 驗證數(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())){
            // 處理查詢參數(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ù)實體和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測試

到此這篇關(guān)于SpringBoot和MybatisPlus實現(xiàn)通用Controller的文章就介紹到這了,更多相關(guān)SpringBoot MybatisPlus 通用Controller內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring事務(wù)管理中@Transactional失效的8個常見場景與解決方案

    Spring事務(wù)管理中@Transactional失效的8個常見場景與解決方案

    在實際開發(fā)中,你是否遇到過明明在方法上添加了@Transactional注解,但事務(wù)卻沒有按預(yù)期工作,本文將深入剖析Spring事務(wù)管理中常見的8個陷阱,幫助你徹底解決這些問題
    2025-11-11
  • java靈活使用mysql中json類型字段存儲數(shù)據(jù)詳解

    java靈活使用mysql中json類型字段存儲數(shù)據(jù)詳解

    在數(shù)據(jù)庫設(shè)計中,面對一對多的關(guān)系,如訂單和商品,可以考慮使用單表存儲而非傳統(tǒng)的分表方式,這篇文章主要介紹了java靈活使用mysql中json類型字段存儲數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下
    2024-09-09
  • Java中LinkedHashSet的實現(xiàn)原理詳解

    Java中LinkedHashSet的實現(xiàn)原理詳解

    這篇文章主要介紹了Java中LinkedHasSet的實現(xiàn)原理詳解,LinkedHashSet?是具有可預(yù)知迭代順序的?Set?接口的哈希表和鏈接列表實現(xiàn),此實現(xiàn)與HashSet?的不同之處在于,后者維護(hù)著一個運行于所有條目的雙重鏈接列表,需要的朋友可以參考下
    2023-09-09
  • springboot使用filter獲取自定義請求頭的實現(xiàn)代碼

    springboot使用filter獲取自定義請求頭的實現(xiàn)代碼

    這篇文章主要介紹了springboot使用filter獲取自定義請求頭的實例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-05-05
  • IDEA導(dǎo)入Eclipse項目全過程

    IDEA導(dǎo)入Eclipse項目全過程

    這篇文章介紹了如何將Eclipse項目導(dǎo)入到IntelliJ IDEA,并詳細(xì)步驟如下:新建一個文件夾,用IntelliJ IDEA打開,將項目導(dǎo)入,等待編譯完成,配置項目環(huán)境和結(jié)構(gòu),注意文件夾名稱可能不同,配置Tomcat,重新編譯項目并啟動
    2025-11-11
  • springboot+dynamicDataSource動態(tài)添加切換數(shù)據(jù)源方式

    springboot+dynamicDataSource動態(tài)添加切換數(shù)據(jù)源方式

    這篇文章主要介紹了springboot+dynamicDataSource動態(tài)添加切換數(shù)據(jù)源方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • SpringBoot路徑映射實現(xiàn)過程圖解

    SpringBoot路徑映射實現(xiàn)過程圖解

    這篇文章主要介紹了SpringBoot路徑映射實現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12
  • spring注解之@Valid和@Validated的區(qū)分總結(jié)

    spring注解之@Valid和@Validated的區(qū)分總結(jié)

    @Validated和@Valid在基本驗證功能上沒有太多區(qū)別,但在分組、注解地方、嵌套驗證等功能上有所不同,下面這篇文章主要給大家介紹了關(guān)于spring注解之@Valid和@Validated區(qū)分的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • Java阻塞隊列必看類:BlockingQueue快速了解大體框架和實現(xiàn)思路

    Java阻塞隊列必看類:BlockingQueue快速了解大體框架和實現(xiàn)思路

    這篇文章主要介紹了Java阻塞隊列必看類:BlockingQueue快速了解大體框架和實現(xiàn)思路,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • Spring?Boot基于?JWT?優(yōu)化?Spring?Security?無狀態(tài)登錄實戰(zhàn)指南

    Spring?Boot基于?JWT?優(yōu)化?Spring?Security?無狀態(tài)登錄實戰(zhàn)指南

    本文介紹如何使用JWT優(yōu)化SpringSecurity實現(xiàn)無狀態(tài)登錄,提高接口安全性,并通過實際操作步驟展示了如何配置JWT參數(shù)、實現(xiàn)JWT登錄接口、認(rèn)證過濾器等,感興趣的朋友跟隨小編一起看看吧
    2025-11-11

最新評論

萨迦县| 应用必备| 宁城县| 永川市| 兴国县| 鲜城| 吴桥县| 焉耆| 海晏县| 历史| 腾冲县| 沙湾县| 昌黎县| 桃园市| 灯塔市| 和平县| 河源市| 莫力| 长寿区| 宜兰县| 海城市| 临澧县| 涞源县| 辰溪县| 台江县| 天水市| 美姑县| 五华县| 武平县| 宿州市| 旅游| 赤水市| 瑞金市| 安义县| 曲麻莱县| 龙游县| 白河县| 平顶山市| 武穴市| 肥乡县| 黎川县|