文章 35
评论 44
浏览 111147
Mybatis-Plus只返回某一个字段的所有记录数据的方法

Mybatis-Plus只返回某一个字段的所有记录数据的方法

需求缘由:因为Mybatis-Plus获得对象中某一个字段值时,一般是默认用get+字段名(),且字段名首字母大写的方法,但是现在我想实现一个功能,就是传入一个字符串参数,这个字符串记录的是想要获取到的字段名,那么如何根据这个字符串来调用对应的get函数呢?

@TableName("servermonitor")  
@Data  
public class Servermonitor {  
    @TableId(type = IdType.AUTO)  
    private Integer id;  
    private double cpu0temp;  
    private double cpu1temp;  
    private double cpu2temp;  
    private double cpu3temp;  
    private double bmctemp;  
    private double psu1temp;  
    private double psu2temp;  
    private double psu1vin;  
    private double psu2vin;  
    private double totalpower;  
    private double cpuwatts;  
    private double memorywatts;  
    private double fanwatts;  
    private double sysfan1;  
    private double sysfan2;  
    private double sysfan3;  
    private double sysfan4;  
    private double sysfan5;  
    private double sysfan6;  
    private double sysfan7;  
    private double sysfan8;  
    //    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")  
    private String time;  
}
  1. 最简单的方法(多个if,else if),缺点很明显,字段多的时候写起来很繁琐。不推荐
public Result<?> getparamsList(@RequestParam(defaultValue = "") String search) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {  
    QueryWrapper<Servermonitor> queryWrapper = new QueryWrapper<>();    
    List<Servermonitor> servermonitorList = servermonitorMapper.selectList(queryWrapper);  
    List<Object> l = new ArrayList<Object>();  
    for(int i = 0; i < servermonitorList.size(); ++i) {  
        if(search == "cpu0temp") l.add(servermonitorList.get(i).getCpu0temp());
        else if(search == "cpu1temp") l.add(servermonitorList.get(i).getCpu1temp());
        else if(...)
		...
		...  
    }  
    return Result.success(l);  
}
  1. 通过构造函数名来调用对应的字段的get方法,这样比较简洁可扩展
public Result<?> getparamsList(@RequestParam(defaultValue = "") String search) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {  
    QueryWrapper<Servermonitor> queryWrapper = new QueryWrapper<>();  
    List<Servermonitor> servermonitorList = servermonitorMapper.selectList(queryWrapper);  
    List<Object> l = new ArrayList<Object>();  
    String searchFunctionName = "get" + (char)(search.charAt(0) - 32) + search.substring(1, search.length());        //字段首字母大写,构造方法名  
    for(int i = 0; i < servermonitorList.size(); ++i) {  
        Servermonitor s = servermonitorList.get(i);  
        Method method = s.getClass().getMethod(searchFunctionName);
        l.add(method.invoke(s));
    }  
    return Result.success(l);  
}

getClass()是获取s这个对象的对象名
Method Class.getMethod(String name, Class<?>… parameterTypes)的作用是获得对象所声明的公开方法,该方法的第一个参数name是要获得方法的名字,第二个参数parameterTypes是按声明顺序标识该方法形参类型。
method.invoke(s) 是执行s对象的method方法。

有更好的方法请评论一下,一起学习交流。


标题:Mybatis-Plus只返回某一个字段的所有记录数据的方法
作者:abandon
地址:HTTPS://www.songsci.com/articles/2022/05/12/1652360062905.html

Life Is Like A Boat

取消