前提:
实体字段的设计为小驼峰类型,数据库字段的设计遵循下划线分割设计对应字段设计的小驼峰原则。
例如实体中的字段为taskType,则数据库的字段为TASK_TYPE。
工具类代码如下:
package com.company.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.*; /** * Map数据转实体或者其他 * @param <T> */ public class MapUtil<T> { private static final Logger logger = LoggerFactory.getLogger(MapUtil.class); private static final SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US); private static final SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd"); private static final SimpleDateFormat sf3 = new SimpleDateFormat("yyyyMMddHHmmss"); @SuppressWarnings({ "unchecked", "rawtypes" }) public T mapToEntity(Class clazz, Map<String, Object> map) { T t = null; if (map == null) return null; try { t = (T) clazz.newInstance(); List<String> list = new ArrayList<String>(); list.add("id"); Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { list.add(f.getName()); } Set<String> set = map.keySet(); Iterator<String> it = set.iterator(); while (it.hasNext()) { try { String name = it.next(); if (!list.contains(name)) { continue; } if (map.get(name) == null) { continue; } PropertyDescriptor pd = new PropertyDescriptor(name, clazz); Method method = pd.getWriteMethod(); if (pd.getPropertyType() == String.class) { method.invoke(t, map.get(name).toString()); } else if (pd.getPropertyType() == Long.class || pd.getPropertyType() == long.class) { method.invoke(t, Long.valueOf(map.get(name).toString())); } else if (pd.getPropertyType() == Integer.class || pd.getPropertyType() == int.class) { method.invoke(t, Integer.valueOf(map.get(name).toString())); } else if (pd.getPropertyType() == Boolean.class || pd.getPropertyType() == boolean.class) { method.invoke(t, Boolean.valueOf(map.get(name).toString())); } else if (pd.getPropertyType() == BigDecimal.class ) { method.invoke(t, BigDecimal.valueOf(Double.valueOf(map.get(name).toString()))); } else if (pd.getPropertyType() == Double.class || pd.getPropertyType() == double.class) { method.invoke(t, Double.valueOf(map.get(name).toString())); } else if (pd.getPropertyType() == Float.class || pd.getPropertyType() == float.class) { method.invoke(t, Float.valueOf(map.get(name).toString())); } else if (pd.getPropertyType() == Byte.class || pd.getPropertyType() == byte.class) { method.invoke(t, Byte