在使用jdbcTemplate时,查询结果转为POJO对象可以使用BeanPropertyRowMapper
,观察这个类可以发现,主要是利用DefaultConversionService
和PropertyDescriptor
这两个Spring的工具,实现属性转换和属性注入;
但是BeanPropertyRowMapper的性能不太好,做了很多安全校验工作,这些工作对于我们转换没有太大的用处,因此笔者基于BeanPropertyRowMapper开发了一个快速将Map转为Pojo的工具类,代码如下:
@Slf4j
public class EntityMapper {
private static final ConcurrentHashMap, Map> CACHE = new ConcurrentHashMap<>(64);
/** ConversionService for binding JDBC values to bean properties. */
private static final DefaultConversionService conversionService = new DefaultConversionService();
static {
//使用默认转换器,并增加时间转换器
conversionService.addConverter(String.class, LocalDateTime.class,
value -> LocalDateTime.parse(value, ISO_LOCAL_DATE_TIME));
conversionService.addConverter(String.class, OffsetDateTime.class,
value -> OffsetDateTime.parse(value, ISO_OFFSET_DATE_TIME));
conversionService.addConverter(String.class, LocalDate.class,
value -> LocalDate.parse(value, ISO_LOCAL_DATE));
conversionService.addConverter(String.class, LocalTime.class,
value -> LocalTime.parse(value, ISO_LOCAL_TIME));
conversionService.addConverter(Timestamp.class, LocalDateTime.class,
value -> value.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
conversionService.addConverter(String.class, Date.class,
value -> {
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = LocalDateTime.parse(value, ISO_LOCAL_DATE_TIME).atZone(zoneId).toInstant();
return Date.from(instant);
});
}
/**
* 增加自定义转换器
*/
public void addConverter(Class sourceType, Class targetType, Converter super S, ? extends T> converter) {
conversionService.addConverter(sourceType, targetType, converter);
}
/**
* map转为对象
*
* @param map map
* @param mappedClass 对象类型
* @return 对象
*/
public static T mapToEntity(Map map, Class mappedClass) {
T mappedObject = BeanUtils.instantiateClass(mappedClass);
Map mappedFields = getMappedFields(mappedClass);
return populate(map, mappedObject, mappedFields);
}
/**
* 转为list
*
* @param mapList map list
* @param mappedClass 对象类型
* @return 对象列表
*/
public static List mapToEntityList(List
使用方法:
String time = ISO_LOCAL_DATE_TIME.format(LocalDateTime.now());
ImmutableMap map =
ImmutableMap.of("name", "AAA",
"age", 12,
"birthday", time);
User user = EntityMapper.mapToEntity(map, User.class);
System.out.println(user);