package com.dsh.guns.modular.system.audit;
|
|
import com.baomidou.mybatisplus.annotation.TableField;
|
import com.baomidou.mybatisplus.annotation.TableName;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.stereotype.Component;
|
|
import javax.annotation.Resource;
|
import java.lang.reflect.Field;
|
import java.util.Collections;
|
import java.util.LinkedHashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.concurrent.ConcurrentHashMap;
|
|
/** 从数据库字段备注自动解析审计展示名;每个实体只查询一次并缓存。 */
|
@Component
|
public class AuditColumnCommentResolver {
|
@Resource private JdbcTemplate jdbcTemplate;
|
private final Map<Class<?>, Map<String, String>> cache = new ConcurrentHashMap<Class<?>, Map<String, String>>();
|
|
public Map<String, String> resolve(Class<?> entityType) {
|
if (entityType == null) return Collections.emptyMap();
|
Map<String, String> cached = cache.get(entityType);
|
if (cached != null) return cached;
|
Map<String, String> labels = load(entityType);
|
cache.put(entityType, labels);
|
return labels;
|
}
|
|
private Map<String, String> load(Class<?> entityType) {
|
TableName tableName = entityType.getAnnotation(TableName.class);
|
if (tableName == null || tableName.value().trim().isEmpty()) return Collections.emptyMap();
|
try {
|
List<Map<String, Object>> columns = jdbcTemplate.queryForList(
|
"SELECT COLUMN_NAME, COLUMN_COMMENT FROM information_schema.COLUMNS "
|
+ "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", tableName.value());
|
Map<String, String> comments = new LinkedHashMap<String, String>();
|
for (Map<String, Object> column : columns) {
|
Object name = column.get("COLUMN_NAME");
|
Object comment = column.get("COLUMN_COMMENT");
|
if (name != null && comment != null && !String.valueOf(comment).trim().isEmpty()) {
|
comments.put(String.valueOf(name), concise(String.valueOf(comment)));
|
}
|
}
|
Map<String, String> result = new LinkedHashMap<String, String>();
|
for (Class<?> type = entityType; type != null && type != Object.class; type = type.getSuperclass()) {
|
for (Field field : type.getDeclaredFields()) {
|
TableField tableField = field.getAnnotation(TableField.class);
|
String column = tableField == null || tableField.value().trim().isEmpty() ? field.getName() : tableField.value();
|
String comment = comments.get(column);
|
if (comment != null) result.put(field.getName(), comment);
|
}
|
}
|
return result;
|
} catch (Exception ignored) {
|
return Collections.emptyMap();
|
}
|
}
|
|
private String concise(String comment) {
|
int bracket = comment.indexOf('(');
|
int asciiBracket = comment.indexOf('(');
|
int cut = bracket >= 0 ? bracket : asciiBracket;
|
return cut > 0 ? comment.substring(0, cut).trim() : comment;
|
}
|
}
|