jpa自定义查询Map、List<Map>转对象处理;bean对象与map、对象集合与map属性集合互转

一、BeanMap

util用例

 

package cc.ash.mvc.util;

import org.springframework.cglib.beans.BeanMap;

import java.util.*;

public class BeanMapUtil<T> {

    /**
     * 将属性键值对map 转为 对象
     */
    public T map2Bean(Map map, T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 将属性键值对map 转为 对象
     */
    public T map2Bean(Map map, Class clz) throws IllegalAccessException, InstantiationException {

        T t = (T) clz.newInstance();
        return map2Bean(map, t);
    }

    /**
     * 将对象 转为属性键值对map
     */
    public Map bean2Map(T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        Map map = new HashMap();

        for(Iterator itKey = beanMap.keySet().iterator(); itKey.hasNext();) {
            Object key = itKey.next();
            map.put(key, beanMap.get(key));
        }
        return map;
    }

    /**
     * 将集合对象 转为属性键值对map集合
     */
    public List<Map> beans2Maps(List<T> list) {
        if(list == null || list.isEmpty()) {
            return null;

        } else {
            final List<Map> maps = new ArrayList<>(list.size());
            list.forEach(t -> maps.add(bean2Map(t)));
            return maps;
        }
    }


    /**
     * 将属性键值对map集合 转为 对象集合
     */
    public List<T> maps2Bean(List<Map> maps, Class clz) throws IllegalAccessException, InstantiationException {

        BeanMap beanMap;
        T bean;
        List<T> list = new ArrayList<>();

        for (Map map : maps) {
            bean = (T) clz.newInstance();
            beanMap = BeanMap.create(bean);
            beanMap.putAll(map);
            list.add(bean);
        }

        return list;
    }

}

 

二、json

可识别大小写下划线等,名称一致即可。不需要数据类型强制对应。(eg: BigInteger -> long)

jpa 查询返回Map 或List<Map>,大概率出现类型转换异常。可使用fastjson将map转为json,再将json解析为所需对象。

需要进一步处理的字段可添加注解

@JSONField(deserialize = false) 处理后调用setter设置。

当tinyint自动转换为boolean类型等,可酌情使用 CONCAT(field, '') 或者ROUND(field, 0)处理。

...

posted @ 2020-05-21 16:03  毁乐乖狂,自有诪张  阅读(1614)  评论(0编辑  收藏  举报