Bläddra i källkod

对查询结果设置i18n map

liangbo.huang 5 dagar sedan
förälder
incheckning
3f553d1d6a

+ 60 - 0
trade-common/src/main/java/com/trade/common/core/service/BaseI18nService.java

@@ -0,0 +1,60 @@
+package com.trade.common.core.service;
+
+import com.baomidou.mybatisplus.core.metadata.TableInfo;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.trade.common.core.domain.BaseI18nEntity;
+import com.trade.common.exception.ServiceException;
+import com.trade.common.utils.I18nUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.jdbc.datasource.DataSourceUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.util.List;
+import java.util.function.BiConsumer;
+
+@Service
+public class BaseI18nService {
+
+    private static final Logger log = LoggerFactory.getLogger(BaseI18nService.class);
+    private DataSource dataSource;
+
+    public BaseI18nService(DataSource dataSource){
+        this.dataSource = dataSource;
+    }
+
+    /**
+     * 更新对象列表的i18n属性
+     * 
+     * @param entityList 实体类集合
+     * @param clazz 类信息
+     * @param <T> BaseI18nEntity
+     */
+    public <T extends BaseI18nEntity> List<T> setI18nMap(List<T> entityList, Class<T> clazz) {
+        exeI18nQuery(entityList, clazz,
+                (tableInfo, connection) -> I18nUtil.setI18nMap(entityList, clazz, tableInfo, connection));
+        return entityList;
+    }
+
+    private <T extends BaseI18nEntity> void exeI18nQuery(List<T> entityList, Class<T> clazz,
+            BiConsumer<TableInfo, Connection> biConsumer) {
+        if (CollectionUtils.isEmpty(entityList)) {
+            return;
+        }
+        TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
+        if (tableInfo == null) {
+            throw new ServiceException("无法获取表信息");
+        }
+        Connection connection = DataSourceUtils.getConnection(dataSource);
+        try {
+            biConsumer.accept(tableInfo, connection);
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            DataSourceUtils.releaseConnection(connection, dataSource);
+        }
+    }
+}