通过数据库查询实体的部分属性
mybatis注解方式
反射
一、功能描述
在部分场景下只需要查询实体的部分属性,另外仅查询部分属性可以减少部分性能开销。本文通过mabatis的注解方式实现以上功能,对此进行记录。另外,通过mybatis从数据库查询回数据后,需要通过工具类将List<Map<String, Object>>类型数据转换为对应的实体对象集合,这部分逻辑也做记录。
二、代码实现
对应的流程和主要实现思路见方法注释。
package blog.field;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.core.ReflectUtils;
import java.beans.FeatureDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 根据字段查询
* 1. 此处没有考虑final或静态字段,且未测试对is开头的bool属性的兼容性能
* 2. 返回值组装为返回对象的时候,针对集合做特殊的处理
* 3. 需要注意,不确认ReflectUtils.getBeanProperties方法是否兼容继承的情况
*/
public class SelectByFieldsTest<T> {
/**
* 反射相关属性缓存
*/
private static final Map<Class, Map<String, PropertyDescriptor>> REFLECT_CACHE = new HashMap<>();
/**
* 实体类和对应表名映射关系,需要配置才可使用,此处没有对该配置做校验
*/
private static final Map<Class, String> CLASS_TABLE_MAP = new HashMap<>();
static {
CLASS_TABLE_MAP.put(User.class, "table_user");
}
/**
* 方法入口
*/
public static <T> void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException {
List<String> fields = Stream.of("userId", "userName", "belongToys").collect(Collectors.toList()<