SpringBoot jpa map转实体类

    default LocalStorage findByFileId(Long fileId) {
        return MapToEntityUtil.toEntity(findByFileIdNative(fileId), LocalStorage.class);
    }

    @Query(value = "SELECT tls.* FROM ua_project_storage  ast join tool_local_storage tls on ast.storage_id = tls.storage_id where ast.storage_id=?1", nativeQuery = true)
    Map<String, Object> findByFileIdNative(Long fileId);

package com.uav.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.uav.common.exception.BusinessException;

import javax.persistence.Column;

import java.lang.reflect.Field;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

public class MapToEntityUtil {

    public static <E> List<E> toEntity(List<Map<String, Object>> mapList, Class<E> entityClass) {
        if (ObjectUtil.isNotEmpty(mapList)) {
            List<E> eList = new ArrayList<>();
            mapList.forEach(objectMap -> eList.add(toEntity(objectMap, entityClass)));
            return eList;
        }
        return null;
    }

    public static <E> E toEntity(Map<String, Object> map, Class<E> entityClass) {
        //统一key名称
        try {
            Map<String, Object> copy = new LinkedHashMap<>();
            //统一key去下划并小写
            map.forEach((k, v) -> copy.put(k.replace("_", "").toLowerCase(), v));
            E entity = entityClass.newInstance();
            List<Field> declaredFields = getAllFiled(entity);
            for (Field field : declaredFields) {
                //优先使用注解
                Column annotation = field.getAnnotation(Column.class);
                String key = "";
                if (annotation != null) {
                    key = annotation.name().toLowerCase().replace("_", "");
                }
                if (StrUtil.isBlank(key)) {
                    key = field.getName().toLowerCase().replace("_", "");
                }
                Object object = copy.get(key);
                if (object != null) {
                    boolean accessible = field.isAccessible();
                    field.setAccessible(true);
                    field.set(entity, null);
                    if (object instanceof BigInteger) {
                        BigInteger bigInteger = (BigInteger) object;
                        if (field.getType() == Long.class) {
                            field.set(entity, bigInteger.longValue());
                        }
                    } else if (object instanceof Timestamp) {
                        Timestamp timestamp = (Timestamp) object;
                        if (field.getType() == LocalDateTime.class) {
                            field.set(entity, timestamp.toLocalDateTime());
                        }
                    } else if (object instanceof Date) {
                        Date date = (Date) object;
                        if (field.getType() == LocalDate.class) {
                            field.set(entity, date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                        } else if (field.getType() == Date.class) {
                            field.set(entity, date);
                        }
                    } else if (object instanceof Byte) {
                        Byte bytes = (Byte) object;
                        if (field.getType() == Byte.class) {
                            field.set(entity, bytes);
                        } else if (field.getType() == Boolean.class) {
                            field.set(entity, bytes.intValue() == 1);
                        }
                    } else if (field.getType() == object.getClass()) {
                        field.set(entity, object);
                    }
                    Object value = field.get(entity);
                    field.setAccessible(accessible);
                    if (value == null) {
                        throw new ClassCastException(String.format("%s.%s 无法将 %s 转换为 %s ", entity.getClass(), field.getName(), object.getClass(), field.getType()));
                    }
                }
            }
            return entity;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BusinessException(ex.getMessage());

        }


    }

    /**
     * 获取自身所以属性且超类属性
     *
     * @param object
     * @return
     */
    private static List<Field> getAllFiled(Object object) {
        Class<Field> clazz = (Class<Field>) object.getClass();
        List<Field> fields = new ArrayList<>();
        while (clazz != null) {
            fields.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = (Class<Field>) clazz.getSuperclass();
        }
        return fields;
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值