性能优化实践:通过数据库查询实体的部分属性

通过数据库查询实体的部分属性


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());
        List<User> users = selectByFieldsService(fields, User.class, "del_flag <> 1");
        System.out.println(users);
    }

    /**
     * 从数据库查询回List<Map<String, Object>>类型的数据,并通过反射将其转化为最终需要的实体对象列表
     */
    private static <T> List<T> selectByFieldsService(List<String> fields, Class<T> clazz, String condition) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        List<Map<String, Object>> listMap = selectByFields(fields, clazz, condition);
        if (listMap != null) {
            List<T> retList = new ArrayList<>(listMap.size());
            Map<String, PropertyDescriptor> cacheReflect = getOrMaintenanceReflect(clazz);
            for (Map<String, Object> fieldMap : listMap) {
                // 循环每个字段,给新实例赋值
                T t = clazz.newInstance();
                for (Map.Entry<String, Object> entry : fieldMap.entrySet()) {
                    PropertyDescriptor tmp = cacheReflect.get(entry.getKey());
                    // 兼容数据库可能存储的逗号分隔的字符串,对应实体中的集合类型
                    Class<?> returnType = tmp.getReadMethod().getReturnType();
                    tmp.getWriteMethod().invoke(t, buildValue(returnType, entry.getValue()));
                }
                retList.add(t);
            }
            return retList;
        }
        return new ArrayList<>();
    }

    private static Object buildValue(Class<?> returnType, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof String) {
            // 如果查询结果是字符串,但是实际需要的类型为其他,则进行转换
            String[] split = StringUtils.split((String) value, ",");
            if ("java.util.List".equals(returnType.getName())) {
                return Arrays.stream(split).collect(Collectors.toList());
            } else if ("java.util.Set".equals(returnType.getName())) {
                return Arrays.stream(split).collect(Collectors.toSet());
            }
        }
        return value;
    }

    /**
     * 从List<Map<String, Object>>转换为实体对象列表使用反射,用到的Method方法查询或进行缓存
     */
    private static <T> Map<String, PropertyDescriptor> getOrMaintenanceReflect(Class<T> clazz) {
        Map<String, PropertyDescriptor> cacheMap = REFLECT_CACHE.get(clazz);
        if (cacheMap == null || cacheMap.isEmpty()) {
            PropertyDescriptor[] beanProperties = ReflectUtils.getBeanProperties(clazz);
            // fixme 此处没有考虑final或静态字段,且未测试对is开头的bool属性的兼容性能
            // Modifier.isStatic(field.getModifiers())
            Map<String, PropertyDescriptor> collect = Arrays.stream(beanProperties).collect(Collectors.toMap(FeatureDescriptor::getName, Function.identity(), (k1, k2) -> k2));
            REFLECT_CACHE.put(clazz, collect);
            return collect;
        }
        return cacheMap;
    }

    /**
     * 调用mapper接口前,对所需参数做转换
     */
    private static List<Map<String, Object>> selectByFields(List<String> fields, Class clazz, String condition) {
        StringJoiner dbFields = new StringJoiner(", ");
        fields.forEach(d -> dbFields.add(String.format("`%s` as `%s`", humpToUnderline(d), d)));
        String table = CLASS_TABLE_MAP.get(clazz);
        System.out.println(String.format("SQL: select %s from %s where %s", dbFields.toString(), table, StringUtils.defaultIfBlank(condition, "1 = 1")));
        return CommonMapper.selectByFields(dbFields.toString(), table, StringUtils.defaultIfBlank(condition, "1 = 1"));
    }

    /**
     * 模拟mybatis-Mapper接口
     */
    interface CommonMapper {
        // @Select("select ${sqlFields} from `${table}` where ${condition}")
        // @ResultType(HashMap.class)
        static List<Map<String, Object>> selectByFields(String sqlFields, String table, String condition) {
            // mock
            if (StringUtils.equals(table, CLASS_TABLE_MAP.get(User.class))) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", 666L);
                map.put("userName", "bob");
                map.put("belongToys", "car,rocket");
                return Collections.singletonList(map);
            }
            return new ArrayList<>();
        }
    }

    /**
     * 工具方法:将驼峰转为下划线
     */
    private static String humpToUnderline(String str) {
        Pattern compile = Pattern.compile("[A-Z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 测试需要的实体类
     */
    static class User {
        private Long userId;
        private String userName;
        private List<String> belongToys;

        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public List<String> getBelongToys() {
            return belongToys;
        }

        public void setBelongToys(List<String> belongToys) {
            this.belongToys = belongToys;
        }

        @Override
        public String toString() {
            return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", belongToys=" + belongToys + '}';
        }
    }
}


总结

以上为比较完整的代码实现,可以直接拷贝调试,注意部分细节需要进一步推敲和完善。
另外,父类转子类也可以使用缓存反射方法的思路进行实现,减小开销,达到性能优化的目的,后续有时间作为补充。

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值