业务场景:公司项目是封装了通用的接口,查询的结果是List<Map<String,Object>>,map的key是数据库里的字段。实体类的字段是小驼峰命名规则,普通的实体类转Map 就会导致key和通用的查询有冲突。如果之前的一些封装的方法是List<Map>就会出现不能用的情况,所以就有了下面的方法。
/**
* 实体类转mAP
* @param entity
* @return
*/
public static<T extends BaseEntity> Map<String, Object> entityToMap(T entity) {
Map<String, Object> map = new HashMap<>();
// 获取实体类的所有字段
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
// 检查字段是否带有@TableField注解
if (field.isAnnotationPresent(TableField.class)) {
TableField tableFieldAnnotation = field.getAnnotation(TableField.class);
String fieldName = tableFieldAnnotation.value(); // 获取注解上的值作为键名
field.setAccessible(true); // 允许访问私有字段
try {
Object value = field.get(entity); // 获取字段的值
map.put(fieldName, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else if (field.isAnnotationPresent(TableId.class)){
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
String fieldName = tableIdAnnotation.value(); // 获取注解上的值作为键名
field.setAccessible(true); // 允许访问私有字段
try {
Object value = field.get(entity); // 获取字段的值
map.put(fieldName, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return map;
}
同理,如果有特殊要求的,可以自己写个注解,用其他的注解也可以