`
yongguang423
  • 浏览: 108472 次
  • 性别: Icon_minigender_1
  • 来自: 山东
社区版块
存档分类
最新评论

Spring JdbcTemplate 查询结果 实体生成工具

 
阅读更多
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by  黄永光
 * User: Administrator
 * Date: 2011-8-11
 * Time: 10:30:15
 * <p/>
 * 将实体工具类,Spring查询对象封装实体工具.
 */

public class EntityTool {

    static Log LOGGER = LogFactory.getLog(EntityTool.class);

    /**
     * 将map转成实体,map中的key必须与实体中的属性名相同才可以转换成功
     *
     * @param entityMap  实体map,属性键值对,其中key为实体的属性名,value为属性的值
     * @param entityType 实体类
     * @param <T>
     * @return
     */
    public static <T> T converToEntity(Map<String, Object> entityMap, Class<T> entityType) {
        T result = null;
        try {
            result = entityType.newInstance();
            Map<String, Field> fieldsMap = getFieldMap(entityType);
            Field field = null;
            for (Map.Entry<String, Object> entry : entityMap.entrySet()) {
                field = fieldsMap.get(entry.getKey().toLowerCase());
                if (field == null) {
                    LOGGER.error("键值" + entry.getKey().toLowerCase() + "在" + entityType.getName() + "中找不到对应的属性!");
                    throw new Exception();

                }
                field.setAccessible(true);
                Object value = entry.getValue();

                if (value == null) {
                    continue;
                    
                }

                if (isBasicType(field.getType())) {
                    //  System.out.println(field.getName()+"="+value);
                    System.out.println(field.getType());

                    if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) {
                        if (value.equals(new Boolean(true) || value.equals(true)) || value.equals(new Boolean(true) || value.equals(true))) {
                            field.set(result, value);
                        } else {
                            if (value.toString().equals("1")) {
                                field.set(result, true);
                            } else {
                                field.set(result, false);
                            }
                        }
                    } else {
                        field.set(result, value);
                    }


                } else {
                    /*
                    设置复合类型属性,只设id如果存在
                     */
                    Class fildType = field.getType();
                    Field idField = null;
                    try {
                        idField = getDeclaredField("id", fildType, true);


                    } catch (NoSuchFieldException e) {
                        continue;
                    }
                    if (idField != null) {
                        idField.setAccessible(true);
                        Object compositeFieldValue = fildType.newInstance();
                        idField.set(compositeFieldValue, value);
                        field.set(result, compositeFieldValue);
                    } else {
                        LOGGER.warn("复合属性" + entry.getKey().toLowerCase() + "没有id属性,没有赋值!");
                    }
                }

            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 得到某类的属性
     * @param fieldName      属性名
     * @param clazz          类
     * @param withSuperClass 是否从父类中取属性
     * @return
     */
    private static Field getDeclaredField(String fieldName, Class clazz, boolean withSuperClass) throws NoSuchFieldException {
        Field field = null;
        try {
            field = clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            if (field == null && withSuperClass) {
                Class superClazz = clazz.getSuperclass();
                if (superClazz != null) {
                    field = getDeclaredField(fieldName, superClazz, withSuperClass);
                }
            } else {
                throw e;
            }
        }


        return field;
    }

    /**
     * 将多个map转换成实体集合
     *
     * @param datas
     * @param entityType
     * @param <E>
     * @return
     */
    public static <E> List<E> convertToEntities(List<Map<String, Object>> datas, Class<E> entityType) {
        List<E> result = new ArrayList<E>();
        E data = null;
        for (Map<String, Object> map : datas) {
            data = converToEntity(map, entityType);
            result.add(data);
            data = null;
        }
        return result;

    }

    /**
     * 判断是不是基本类型
     *
     * @param type
     * @return
     */
    public static boolean isBasicType(Class type) {

        if (type.isPrimitive()) {
            return true;
        }

        if (type.getPackage().getName().equals("java.lang") || type.getPackage().getName().equals(("java.util"))) {
            return true;
        } else if (type.equals(java.sql.Date.class)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 得到某个类的属性map key为属性名,value为属性
     *
     * @param entityClass
     * @return
     */
    public static Map<String, Field> getFieldMap(Class entityClass) {
        Field[] fields = entityClass.getDeclaredFields();
        Map<String, Field> fieldsMap = new HashMap<String, Field>();

        for (Field field : fields) {
            fieldsMap.put(field.getName().toLowerCase(), field);

        }
        Class superclass = entityClass.getSuperclass();

        if (superclass != null) {
            fieldsMap.putAll(getFieldMap(superclass));

        }
        return fieldsMap;
    }

    public static void main(String[] args) {
        /*Map<String,Field> fields=  getFieldMap(User.class);
        for(Map.Entry<String,Field> entry:fields.entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue());

        }*/
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", null);
        map.put("userId", null);
        map.put("employee", null);
        map.put("password", null);
        map.put("userStatus", null);
        map.put("historyPwdList", null);
        map.put("statusChangeTime", null);
        map.put("updateTimeStamp", null);
        map.put("passwordUpdateTime", null);
        map.put("createTimeStamp", null);
        map.put("removed", null);

        User user = converToEntity(map, User.class);

        System.out.println(user.getId());


    }
}

 

0
4
分享到:
评论
1 楼 osacar 2011-10-03  
写得不错啊。
相当实用啊!

相关推荐

Global site tag (gtag.js) - Google Analytics