SpringBoot基于注解實(shí)現(xiàn)數(shù)據(jù)庫(kù)字段回填的完整方案
本文主要介紹一種便捷的數(shù)據(jù)庫(kù)字段回填方案,比如存儲(chǔ)的關(guān)聯(lián)ID,但是需要查詢出來(lái)名稱,我們就不用再進(jìn)行手動(dòng)查詢了,用注解自動(dòng)查詢數(shù)據(jù)庫(kù)關(guān)聯(lián)出來(lái),下面的案例基于 SpringBoot + mybatis-plus + mysql 。
以下是完整的實(shí)現(xiàn)代碼:
數(shù)據(jù)庫(kù)表
CREATE TABLE `user` ( `id` int(11) NOT NULL, `code` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `home_page` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; CREATE TABLE `bom` ( `id` int(11) NOT NULL, `code` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `size` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; CREATE TABLE `product` ( `id` int(11) NOT NULL, `code` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `bom_id` int(11) DEFAULT NULL, `user_code` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
pom.xml
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.39</version>
</dependency>
</dependencies>
RelationField
注解類
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RelationField {
/**
* 數(shù)據(jù)源Mapper
*/
Class<? extends BaseMapper<?>> source();
/**
* 關(guān)聯(lián)條件字段(實(shí)體字段名)
*/
String condition();
/**
* 關(guān)聯(lián)條件值來(lái)源(函數(shù)式表達(dá)式)
*/
String conditionValue();
/**
* 要映射的字段(實(shí)體字段名)
*/
String target();
}
RelationFieldMapping
數(shù)據(jù)轉(zhuǎn)換
@Slf4j
@Component
public class RelationFieldMapping {
// 使用ConcurrentHashMap保證線程安全,緩存類級(jí)別的映射配置
private static final Map<Class<?>, Map<MappingConfig, List<CacheTask>>> MAPPING_CONFIG_CACHE = new ConcurrentHashMap<>();
@Autowired
private ApplicationContext applicationContext;
/**
* 映射單個(gè)對(duì)象的關(guān)聯(lián)字段
*/
public void map(Object dto) {
if (dto == null) {
return;
}
try {
Map<MappingConfig, List<MappingTask>> taskGroups = groupMappingTasks(dto);
for (Map.Entry<MappingConfig, List<MappingTask>> entry : taskGroups.entrySet()) {
executeBatchMapping(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
log.error("映射對(duì)象關(guān)聯(lián)字段失敗: {}", dto.getClass().getSimpleName(), e);
}
}
/**
* 批量映射對(duì)象列表的關(guān)聯(lián)字段
*/
public <T> void map(List<T> dtos) {
if (dtos == null || dtos.isEmpty()) {
return;
}
try {
if (dtos.size() == 1) {
map(dtos.getFirst());
return;
}
Map<MappingConfig, List<MappingTask>> taskGroups = groupCrossObjectTasks(dtos);
for (Map.Entry<MappingConfig, List<MappingTask>> entry : taskGroups.entrySet()) {
executeBatchMapping(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
log.error("批量映射關(guān)聯(lián)字段失敗", e);
}
}
/**
* 緩存類級(jí)別的映射配置(線程安全版本)
*/
private Map<MappingConfig, List<CacheTask>> getCachedMappingConfigs(Class<?> clazz) {
return MAPPING_CONFIG_CACHE.computeIfAbsent(clazz, k -> {
Field[] fields = clazz.getDeclaredFields();
Map<MappingConfig, List<CacheTask>> configGroups = new HashMap<>();
for (Field field : fields) {
CacheTask cacheTask = createCacheTask(field);
if (cacheTask != null) {
MappingConfig config = new MappingConfig(
cacheTask.mapperClass,
cacheTask.conditionField
);
configGroups.computeIfAbsent(config, k1 -> new ArrayList<>()).add(cacheTask);
}
}
return configGroups;
});
}
/**
* 分組映射任務(wù)
*/
private Map<MappingConfig, List<MappingTask>> groupMappingTasks(Object dto) {
Map<MappingConfig, List<CacheTask>> cachedConfigs = getCachedMappingConfigs(dto.getClass());
if (cachedConfigs.isEmpty()) {
return Collections.emptyMap();
}
Map<MappingConfig, List<MappingTask>> taskGroups = new HashMap<>();
cachedConfigs.forEach((config, cacheTasks) -> {
for (CacheTask cacheTask : cacheTasks) {
MappingTask task = createMappingTask(dto, cacheTask);
taskGroups.computeIfAbsent(config, k -> new ArrayList<>()).add(task);
}
});
return taskGroups;
}
/**
* 創(chuàng)建映射任務(wù)
*/
private MappingTask createMappingTask(Object dto, CacheTask cacheTask) {
// 直接從DTO中提取條件字段的值(注意:conditionValue是字段名,不是值)
Object conditionValue = extractEntityField(dto, cacheTask.conditionValue);
return new MappingTask(
dto,
cacheTask.targetField,
cacheTask.mapperClass,
cacheTask.conditionField,
cacheTask.targetFieldName,
conditionValue
);
}
/**
* 創(chuàng)建緩存任務(wù)
*/
private CacheTask createCacheTask(Field targetField) {
RelationField annotation = targetField.getAnnotation(RelationField.class);
if (annotation == null) {
return null;
}
return new CacheTask(
targetField,
annotation.source(),
annotation.condition(),
annotation.target(),
annotation.conditionValue()
);
}
/**
* 分組跨對(duì)象映射任務(wù)
*/
private <T> Map<MappingConfig, List<MappingTask>> groupCrossObjectTasks(List<T> dtos) {
Map<MappingConfig, List<MappingTask>> taskGroups = new HashMap<>();
for (T dto : dtos) {
Map<MappingConfig, List<MappingTask>> dtoTasks = groupMappingTasks(dto);
dtoTasks.forEach((config, tasks) -> taskGroups.computeIfAbsent(config, k -> new ArrayList<>()).addAll(tasks));
}
return taskGroups;
}
/**
* 執(zhí)行批量映射
*/
private void executeBatchMapping(MappingConfig config, List<MappingTask> tasks) {
if (tasks.isEmpty()) {
return;
}
try {
BaseMapper<Object> mapper = getMapper(config.mapperClass);
Set<Object> distinctValues = extractDistinctValues(tasks);
if (distinctValues.isEmpty()) {
return;
}
// 獲取所有需要查詢的目標(biāo)字段
List<String> targetFields = tasks.stream()
.map(task -> task.targetFieldName)
.distinct()
.collect(Collectors.toList());
Map<Object, Object> entityMap = queryEntities(mapper, config, distinctValues, targetFields);
applyMappings(tasks, entityMap);
} catch (Exception e) {
log.error("執(zhí)行批量映射失敗: {}", config, e);
}
}
/**
* 獲取Mapper實(shí)例
*/
@SuppressWarnings("unchecked")
private BaseMapper<Object> getMapper(Class<?> mapperClass) {
try {
return (BaseMapper<Object>) applicationContext.getBean(mapperClass);
} catch (Exception e) {
throw new RuntimeException("獲取Mapper失敗: " + mapperClass.getName(), e);
}
}
/**
* 提取去重值
*/
private Set<Object> extractDistinctValues(List<MappingTask> tasks) {
return tasks.stream()
.map(task -> task.conditionValue)
.collect(Collectors.toSet());
}
/**
* 查詢實(shí)體數(shù)據(jù)
*/
private Map<Object, Object> queryEntities(BaseMapper<Object> mapper, MappingConfig config, Set<Object> values, List<String> targetFields) {
try {
QueryWrapper<Object> queryWrapper = buildQueryWrapper(config, values, targetFields);
List<Object> entities = mapper.selectList(queryWrapper);
Map<Object, Object> resultMap = buildResultMap(entities, config.conditionField);
log.debug("查詢完成: {} -> {}條記錄 (目標(biāo)字段: {})", config, resultMap.size(), targetFields);
return resultMap;
} catch (Exception e) {
throw new RuntimeException("查詢實(shí)體數(shù)據(jù)失敗: " + config, e);
}
}
/**
* 構(gòu)建查詢條件
*/
private QueryWrapper<Object> buildQueryWrapper(MappingConfig config, Set<Object> values, List<String> targetFields) {
QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
// 轉(zhuǎn)換條件字段名為數(shù)據(jù)庫(kù)字段名(駝峰轉(zhuǎn)下劃線)
String dbConditionField = StrUtil.toUnderlineCase(config.conditionField);
if (values.size() == 1) {
queryWrapper.eq(dbConditionField, values.iterator().next());
} else {
queryWrapper.in(dbConditionField, values);
}
// 如果targetFields為空,則查詢所有字段;否則查詢指定字段
if (targetFields.isEmpty()) {
return queryWrapper;
}
// 查詢所有需要的字段:條件字段 + 所有目標(biāo)字段(轉(zhuǎn)換為數(shù)據(jù)庫(kù)字段名)
String[] selectFields = new String[targetFields.size() + 1];
selectFields[0] = dbConditionField;
for (int i = 0; i < targetFields.size(); i++) {
selectFields[i + 1] = StrUtil.toUnderlineCase(targetFields.get(i));
}
queryWrapper.select(selectFields);
return queryWrapper;
}
/**
* 構(gòu)建結(jié)果映射
*/
private Map<Object, Object> buildResultMap(List<Object> entities, String conditionField) {
return entities.stream()
.collect(Collectors.toMap(
entity -> extractEntityField(entity, conditionField),
Function.identity(),
(existing, replacement) -> existing // 處理重復(fù)key
));
}
/**
* 應(yīng)用映射結(jié)果
*/
private void applyMappings(List<MappingTask> tasks, Map<Object, Object> entityMap) {
for (MappingTask task : tasks) {
try {
Object entity = entityMap.get(task.conditionValue);
if (entity != null) {
Object fieldValue = extractEntityField(entity, task.targetFieldName);
setFieldValue(task.dto, task.targetField, fieldValue);
}
} catch (Exception e) {
log.warn("應(yīng)用映射失敗: {}.{}",
task.dto.getClass().getSimpleName(), task.targetField.getName(), e);
}
}
}
/**
* 提取實(shí)體字段值
*/
private Object extractEntityField(Object entity, String fieldName) {
return ReflectUtil.getFieldValue(entity, StrUtil.toCamelCase(fieldName));
}
/**
* 設(shè)置字段值
*/
private void setFieldValue(Object obj, Field field, Object value) {
ReflectUtil.setFieldValue(obj, field, value);
}
// 內(nèi)部類定義
private record MappingTask(Object dto, Field targetField, Class<? extends BaseMapper<?>> mapperClass,
String conditionField, String targetFieldName, Object conditionValue) {
}
private record CacheTask(Field targetField, Class<? extends BaseMapper<?>> mapperClass,
String conditionField, String targetFieldName, String conditionValue) {
}
private record MappingConfig(Class<? extends BaseMapper<?>> mapperClass, String conditionField) {
@Override
public String toString() {
return String.format("MappingConfig[%s, condition=%s]",
mapperClass.getSimpleName(), conditionField);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MappingConfig that = (MappingConfig) o;
return Objects.equals(mapperClass, that.mapperClass) &&
Objects.equals(conditionField, that.conditionField);
}
@Override
public int hashCode() {
return Objects.hash(mapperClass, conditionField);
}
}
}
基礎(chǔ)的一些代碼
@Data
@TableName("bom")
public class BomEntity {
private Long id;
private String code;
private String name;
private String size;
}
@Data
@TableName("product")
public class ProductEntity {
private Long id;
private String code;
private String name;
private Long bomId;
private String userCode;
}
@Data
@TableName("user")
public class UserEntity {
private Long id;
private String code;
private String name;
private String homePage;
}
@Repository
public interface BomMapper extends BaseMapper<BomEntity> {
}
@Repository
public interface ProductMapper extends BaseMapper<ProductEntity> {
}
@Repository
public interface UserMapper extends BaseMapper<UserEntity> {
}
application.yml
spring:
datasource:
url: jdbc:mysql://192.168.8.134:30635/test_1?useSSL=false
username: super_admin
password: super_admin
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
案例代碼
ProductDetailRes
@Data
public class ProductDetailRes {
private Long id;
private String code;
private String name;
private Long bomId;
@RelationField(source = BomMapper.class, condition = "id", conditionValue = "bomId", target = "name")
private String bomName;
@RelationField(source = BomMapper.class, condition = "id", conditionValue = "bomId", target = "size")
private String bomSize;
private String userCode;
@RelationField(source = UserMapper.class, condition = "code", conditionValue = "userCode", target = "name")
private String userName;
@RelationField(source = UserMapper.class, condition = "code", conditionValue = "userCode", target = "homePage")
private String userHomePage;
}
ProductService
@Service
public class ProductService {
@Autowired
private ProductMapper productMapper;
@Autowired
private RelationFieldMapping relationFieldMapping;
public ProductDetailRes detail(Long id) {
ProductEntity productEntity = productMapper.selectById(id);
ProductDetailRes productDetailRes = BeanUtil.copyProperties(productEntity, ProductDetailRes.class);
relationFieldMapping.map(productDetailRes);
return productDetailRes;
}
public List<ProductDetailRes> list() {
List<ProductEntity> productEntityList = productMapper.selectList(null);
List<ProductDetailRes> productDetailResList = BeanUtil.copyToList(productEntityList, ProductDetailRes.class);
relationFieldMapping.map(productDetailResList);
return productDetailResList;
}
}
ProductController
@RestController
@RequestMapping(value = "product")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping(value = "detail")
public ProductDetailRes detail(Long id) {
return productService.detail(id);
}
@GetMapping(value = "list")
public List<ProductDetailRes> list() {
return productService.list();
}
}
curl [http://localhost:8080/product/list](http://localhost:8080/product/list)
curl [http://localhost:8080/product/detail?id=1](http://localhost:8080/product/detail?id=1)

到此這篇關(guān)于SpringBoot基于注解實(shí)現(xiàn)數(shù)據(jù)庫(kù)字段回填的完整方案的文章就介紹到這了,更多相關(guān)SpringBoot數(shù)據(jù)庫(kù)字段回填內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java代碼抓取網(wǎng)頁(yè)郵箱的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇java代碼抓取網(wǎng)頁(yè)郵箱的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06
IDEA中創(chuàng)建maven項(xiàng)目引入相關(guān)依賴無(wú)法下載jar問(wèn)題及解決方案
這篇文章主要介紹了IDEA中創(chuàng)建maven項(xiàng)目引入相關(guān)依賴無(wú)法下載jar問(wèn)題及解決方案,本文通過(guò)圖文并茂的形式給大家分享解決方案,需要的朋友可以參考下2020-07-07
Java基本知識(shí)點(diǎn)之變量和數(shù)據(jù)類型
這篇文章主要給大家介紹了關(guān)于Java基本知識(shí)點(diǎn)之變量和數(shù)據(jù)類型的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
淺談Java中File文件的創(chuàng)建以及讀寫(xiě)
文中有非常詳細(xì)的步驟介紹了Java中file文件的創(chuàng)建以及讀寫(xiě),對(duì)剛開(kāi)始學(xué)習(xí)java的小伙伴們很有幫助,而且下文有非常詳細(xì)的代碼示例及注釋哦,需要的朋友可以參考下2021-05-05
SpringBoot實(shí)現(xiàn)短信發(fā)送及手機(jī)驗(yàn)證碼登錄
本文主要介紹了SpringBoot實(shí)現(xiàn)短信發(fā)送及手機(jī)驗(yàn)證碼登錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
springboot?ElasticSearch如何配置自定義轉(zhuǎn)換器ElasticsearchCustomConver
這篇文章主要介紹了springboot?ElasticSearch如何配置自定義轉(zhuǎn)換器ElasticsearchCustomConversions問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
超細(xì)致講解Spring框架 JdbcTemplate的使用
在之前的Javaweb學(xué)習(xí)中,學(xué)習(xí)了手動(dòng)封裝JdbcTemplate,其好處是通過(guò)(sql語(yǔ)句+參數(shù))模板化了編程。而真正的JdbcTemplate類,是Spring框架為我們寫(xiě)好的。它是 Spring 框架中提供的一個(gè)對(duì)象,是對(duì)原始 Jdbc API 對(duì)象的簡(jiǎn)單封裝。2021-09-09
Spring使用IOC與DI實(shí)現(xiàn)完全注解開(kāi)發(fā)
IOC也是Spring的核心之一了,之前學(xué)的時(shí)候是采用xml配置文件的方式去實(shí)現(xiàn)的,后來(lái)其中也多少穿插了幾個(gè)注解,但是沒(méi)有說(shuō)完全采用注解實(shí)現(xiàn)。那么這篇文章就和大家分享一下,全部采用注解來(lái)實(shí)現(xiàn)IOC + DI2022-09-09

