Commit 32d321b4 authored by 楊慶堂's avatar 楊慶堂

多語檔一次讀出來

parent 7c1f5587
......@@ -25,7 +25,7 @@ import com.google.common.cache.CacheBuilder;
/**
* Spring data 取出後進行多國語系的替換
*
* 快取多語資料 30 分鐘
*/
public class I18NPostProcessor implements MethodInterceptor {
private Logger logger = LoggerFactory.getLogger(getClass());
......@@ -94,28 +94,33 @@ public class I18NPostProcessor implements MethodInterceptor {
String table = i18n.table();
String idColumn = i18n.id();
String key = table + "_" + id + "_" + language;
Map<String, String> result = cache.getIfPresent(key);
Map<String, Map<String, String>> translateTable = translateTable(table, language, i18n.mapping(), idColumn);
return translateTable.get(id);
}
private Map<String, Map<String, String>> translateTable(String table, String language, I18NTranslate[] mapping, String idColumn) {
String key = "Table:" + table + "_" + language;
Map<String, Map<String, String>> result = cache.getIfPresent(key);
if (result == null) {
logger.trace("translate query, table: {}", table);
String sql =
String.format("select * from %s where %s = ? and languageCode = ?", table, idColumn);
String.format("select * from %s where languageCode = ?", table);
Query query = em.createNativeQuery(sql);
SQLQuery query1 = query.unwrap(org.hibernate.SQLQuery.class);
query1.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
for (I18NTranslate i18nTranslate : i18n.mapping()) {
query1.addScalar(idColumn);
for (I18NTranslate i18nTranslate : mapping) {
query1.addScalar(i18nTranslate.column());
}
query.setParameter(1, id);
query.setParameter(2, language);
query.setParameter(1, language);
List<Map<String, String>> result1 = query.getResultList();
if (!result1.isEmpty()) {
result = result1.get(0);
result = new HashMap<>();
for (Map<String, String> map : result1) {
result.put(map.get(idColumn), map);
}
cache.put(key, result);
} else
cache.put(key, new HashMap<>());
}
return result;
}
......
......@@ -9,6 +9,14 @@ import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.core.support.RepositoryProxyPostProcessor;
/**
* 將 Spring JPA 的讀取套上 i18n 轉換
* @author scott.yang
*
* @param <R>
* @param <T>
* @param <I>
*/
public class I18NRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
extends JpaRepositoryFactoryBean<R, T, I> {
......
......@@ -9,7 +9,7 @@ import java.lang.annotation.Target;
@Target({ElementType.TYPE})
public @interface I18NTranslates {
/**
* 對應的 id
* 翻譯表格對應的資料 id 欄位
*
* @return
*/
......@@ -23,7 +23,7 @@ public @interface I18NTranslates {
String table() default "";
/**
* 資料對應
* 要翻譯的資料對應
*/
I18NTranslate[] mapping();
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment