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;
    }
}

总结

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

相关推荐
HehuaTang21 分钟前
requests 调大并对齐 limits 提升POD高负载场景下性能
java·docker·kubernetes
SuperherRo34 分钟前
JAVA攻防-Shiro专题&key利用链&CB1链分析&入口点&调用链&执行地&Class加载
java·shiro·反序列化·cb1链
韩立学长37 分钟前
基于Springboot流浪动物救助系统o8g44kwc(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
沛沛老爹42 分钟前
Web开发者转型AI:Agent Skills版本控制与管理实战——从Git到AI技能仓库
java·前端·人工智能·git·架构·rag
我命由我123451 小时前
充血模型与贫血模型
java·服务器·后端·学习·架构·java-ee·系统架构
重学一遍1 小时前
Spring Security + JWT + Redis 的认证授权系统
java·redis·spring
daladongba1 小时前
Spring Cloud Gateway
java·spring cloud·gateway
qq_318121591 小时前
互联网大厂Java面试故事:在线教育微服务架构、缓存优化与AI智能教学全流程解析
java·spring boot·redis·微服务·kafka·spring security·在线教育
小镇学者1 小时前
【other】Goofy Node
后端
sunddy_x1 小时前
Java反射
java