Springboot根据mapper名称动态获取表数据(如ID)

前言

例如:开发过程中,有全选跨页的需求(点击列表页上的全选会把所有页面的数据都勾选上),需要返回全部id作为标志。

故需要一个接口返回表的所有id对象供前端使用,为此,写了个通用的接口。只需提供注册在Spring中的mapper名称即可。


具体代码

java 复制代码
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fas.fasservice.exception.ServiceException;
import com.fas.fasservice.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor()
public class DynamicQueryService {

    private final ApplicationContext applicationContext;

    /**
     * 根据类型动态获取对应的 Mapper 并执行查询操作
     *
     * @param mapperName Mapper 的名称,例如 "studentMapper" 或 "scoreMapper"
     */
    @SuppressWarnings("all")
    public <T> List<String> getIdsByMapperName(String mapperName) {

        if (StringUtil.isNull(mapperName)) {
            throw new ServiceException("参数不能为空");
        }
        BaseMapper<T> mapper;
        try {
            mapper = (BaseMapper<T>) applicationContext.getBean(mapperName);
        } catch (Exception e) {
            throw new ServiceException("无对应的mapper对象");
        }

        // 构造查询条件
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("delete_flag", "0");

        List<T> ts = mapper.selectList(queryWrapper);
        return processList(ts);
    }

    public static <T> List<String> processList(List<T> ts) {
        List<String> result = new ArrayList<>();
        if (ts == null || ts.isEmpty()) {
            return result;
        }
        // 获取第一个元素的类信息
        Class<?> clazz = ts.get(0).getClass();
        try {
            // 获取getId方法
            Method getIdMethod = clazz.getMethod("getId");
            for (T t : ts) {
                Object id = getIdMethod.invoke(t);
                result.add(String.valueOf(id));
            }
        } catch (Exception e) {
            throw new ServiceException("调用getId方法失败");
        }
        return result;
    }
}

总结

可以根据提供的方法去做定制,无非就是加判断加条件,以达到自己的目的。

相关推荐
迦蓝叶7 分钟前
JAiRouter v1.0.0 正式发布:企业级 AI 服务网关的开源解决方案
java·运维·人工智能·网关·spring·ai·开源
咖啡教室10 分钟前
每日一个计算机小知识:Host
后端
安卓开发者13 分钟前
鸿蒙NEXT应用接入快捷栏:一键直达,提升用户体验
java·harmonyos·ux
yudiandian201420 分钟前
03 Eclipse 配置 JDK 环境
java·ide·eclipse
_码力全开_20 分钟前
P1005 [NOIP 2007 提高组] 矩阵取数游戏
java·c语言·c++·python·算法·矩阵·go
咖啡教室23 分钟前
每日一个计算机小知识:Bit和Byte(比特和字节)
后端
陈一Tender24 分钟前
JavaWeb后端实战(登录认证 & 令牌技术 & 拦截器 & 过滤器)
java·开发语言·spring boot·mysql
Camel卡蒙24 分钟前
红黑树详细介绍(五大规则、保持平衡操作、Java实现)
java·开发语言·算法
咖啡教室33 分钟前
每日一个计算机小知识:Linux
linux·后端
IT_陈寒1 小时前
Vite 5个隐藏技巧让你的项目构建速度提升50%,第3个太香了!
前端·人工智能·后端