diff --git a/src/main/java/com/sondertara/joya/annotation/TableAlias.java b/src/main/java/com/sondertara/joya/annotation/TableAlias.java
index f22db35..9cb9dc3 100644
--- a/src/main/java/com/sondertara/joya/annotation/TableAlias.java
+++ b/src/main/java/com/sondertara/joya/annotation/TableAlias.java
@@ -6,21 +6,16 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-
/**
* 表别名
*
* @author huangxiaohu
*/
-
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableAlias {
- /**
- * 表的别名 数据权限使用,应该与模板查询中的别名一致, 默认: a
- */
- String value() default "a";
-
-}
\ No newline at end of file
+ /** 表的别名 数据权限使用,应该与模板查询中的别名一致, 默认: a */
+ String value() default "a";
+}
diff --git a/src/main/java/com/sondertara/joya/cache/AliasThreadLocalCache.java b/src/main/java/com/sondertara/joya/cache/AliasThreadLocalCache.java
index b49e7bb..e34df37 100644
--- a/src/main/java/com/sondertara/joya/cache/AliasThreadLocalCache.java
+++ b/src/main/java/com/sondertara/joya/cache/AliasThreadLocalCache.java
@@ -1,6 +1,5 @@
package com.sondertara.joya.cache;
-
import com.sondertara.common.exception.TaraException;
import com.sondertara.common.function.TaraFunction;
import com.sondertara.common.lang.Assert;
@@ -26,178 +25,194 @@
/**
* (non-Javadoc)
- *
- * Alias cache based on ThreadLocal
- * Save the relationship of query table name and table alias
+ *
+ *
Alias cache based on ThreadLocal Save the relationship of query table name and table alias
*
* @author huangxiaohu
*/
public final class AliasThreadLocalCache {
- /**
- * The pattern for get part of method
- */
- private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
- /**
- * The pattern for set part of method
- */
- private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
-
- /**
- * (non-Javadoc)
- * set table alias
- *
- * the table alias will be like t0,t1...
- *
- * @param aClass the entity class
- */
- @SuppressWarnings("unchecked")
- public static void generateTableAlias(Class> aClass) {
-
- TableStruct tableStruct = LocalEntityCache.getInstance().get(aClass.getName()).orElseThrow(() -> new TaraException("No entity found with class:{}", aClass.getName()));
- LinkedHashMap aliasMap = (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
-
- TableAlias aliasDTO = new TableAlias();
- aliasDTO.setClassName(aClass.getName());
- aliasDTO.setTableName(tableStruct.getTableName());
- aliasDTO.setAliasName(StringFormatter.format("t{}", aliasMap.size()));
- aliasMap.putIfAbsent(aClass.getName(), aliasDTO);
- }
-
- @SuppressWarnings("unchecked")
- public static void generateTableAlias(String tableAndAlias) {
- Assert.notBlank(tableAndAlias);
- String[] strings = tableAndAlias.split(" ");
-
- LocalEntityCache.getInstance().get(strings[0].toLowerCase()).ifPresent(t -> {
- LinkedHashMap aliasMap = (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
-
- TableAlias aliasDTO = new TableAlias();
- aliasDTO.setClassName(t.getClassName());
- aliasDTO.setTableName(t.getTableName());
- aliasDTO.setAliasName(StringFormatter.format("t{}", aliasMap.size()));
- aliasMap.putIfAbsent(t.getClassName(), aliasDTO);
- });
- }
-
- /**
- * (non-Javadoc)
- * Get the column information
- *
- * @param taraSqlFn the apply function
- * @param generic
- * @return Object contain
- */
- @SuppressWarnings("unchecked")
- public static ColumnAlias getColumn(TaraFunction taraSqlFn) {
- try {
- Method method = taraSqlFn.getClass().getDeclaredMethod("writeReplace");
- method.setAccessible(Boolean.TRUE);
- SerializedLambda serializedLambda = (SerializedLambda) method.invoke(taraSqlFn);
- String implClass = serializedLambda.getImplClass();
- String getter = serializedLambda.getImplMethodName();
-
- String className = implClass.replace("/", ".");
-
- Optional optional = LocalEntityCache.getInstance().get(className);
- // get the field name
- if (GET_PATTERN.matcher(getter).matches()) {
- getter = getter.substring(3);
- } else if (IS_PATTERN.matcher(getter).matches()) {
- getter = getter.substring(2);
- }
- String finalGetter = getter;
- AtomicReference tableName = new AtomicReference<>();
- String columnName = optional.map(tableDTO -> {
- Map map = tableDTO.getFields();
- tableName.set(tableDTO.getTableName());
-
- String fieldName = StringUtils.lowerFirst(finalGetter);
- if (map.containsKey(fieldName)) {
- return map.get(fieldName);
- }
- throw new EntityNotFoundException("No column found by " + finalGetter);
- }).orElseThrow(() -> new EntityNotFoundException("no entity found for " + implClass));
- LinkedHashMap aliasMap = (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
- TableAlias tableAlias = aliasMap.computeIfAbsent(className, k -> {
+ /** The pattern for get part of method */
+ private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
+ /** The pattern for set part of method */
+ private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
+
+ /**
+ * (non-Javadoc) set table alias
+ *
+ * the table alias will be like t0,t1...
+ *
+ * @param aClass the entity class
+ */
+ @SuppressWarnings("unchecked")
+ public static void generateTableAlias(Class> aClass) {
+
+ TableStruct tableStruct =
+ LocalEntityCache.getInstance()
+ .get(aClass.getName())
+ .orElseThrow(
+ () -> new TaraException("No entity found with class:{}", aClass.getName()));
+ LinkedHashMap aliasMap =
+ (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
+
+ TableAlias aliasDTO = new TableAlias();
+ aliasDTO.setClassName(aClass.getName());
+ aliasDTO.setTableName(tableStruct.getTableName());
+ aliasDTO.setAliasName(StringFormatter.format("t{}", aliasMap.size()));
+ aliasMap.putIfAbsent(aClass.getName(), aliasDTO);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static void generateTableAlias(String tableAndAlias) {
+ Assert.notBlank(tableAndAlias);
+ String[] strings = tableAndAlias.split(" ");
+
+ LocalEntityCache.getInstance()
+ .get(strings[0].toLowerCase())
+ .ifPresent(
+ t -> {
+ LinkedHashMap aliasMap =
+ (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
+
+ TableAlias aliasDTO = new TableAlias();
+ aliasDTO.setClassName(t.getClassName());
+ aliasDTO.setTableName(t.getTableName());
+ aliasDTO.setAliasName(StringFormatter.format("t{}", aliasMap.size()));
+ aliasMap.putIfAbsent(t.getClassName(), aliasDTO);
+ });
+ }
+
+ /**
+ * (non-Javadoc) Get the column information
+ *
+ * @param taraSqlFn the apply function
+ * @param generic
+ * @return Object contain
+ */
+ @SuppressWarnings("unchecked")
+ public static ColumnAlias getColumn(TaraFunction taraSqlFn) {
+ try {
+ Method method = taraSqlFn.getClass().getDeclaredMethod("writeReplace");
+ method.setAccessible(Boolean.TRUE);
+ SerializedLambda serializedLambda = (SerializedLambda) method.invoke(taraSqlFn);
+ String implClass = serializedLambda.getImplClass();
+ String getter = serializedLambda.getImplMethodName();
+
+ String className = implClass.replace("/", ".");
+
+ Optional optional = LocalEntityCache.getInstance().get(className);
+ // get the field name
+ if (GET_PATTERN.matcher(getter).matches()) {
+ getter = getter.substring(3);
+ } else if (IS_PATTERN.matcher(getter).matches()) {
+ getter = getter.substring(2);
+ }
+ String finalGetter = getter;
+ AtomicReference tableName = new AtomicReference<>();
+ String columnName =
+ optional
+ .map(
+ tableDTO -> {
+ Map map = tableDTO.getFields();
+ tableName.set(tableDTO.getTableName());
+
+ String fieldName = StringUtils.lowerFirst(finalGetter);
+ if (map.containsKey(fieldName)) {
+ return map.get(fieldName);
+ }
+ throw new EntityNotFoundException("No column found by " + finalGetter);
+ })
+ .orElseThrow(() -> new EntityNotFoundException("no entity found for " + implClass));
+ LinkedHashMap aliasMap =
+ (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
+ TableAlias tableAlias =
+ aliasMap.computeIfAbsent(
+ className,
+ k -> {
TableAlias aliasDTO = new TableAlias();
aliasDTO.setTableName(tableName.get());
aliasDTO.setClassName(className);
aliasDTO.setAliasName(StringFormatter.format("t{}", aliasMap.size()));
return aliasDTO;
- });
- ColumnAlias columnAlias = new ColumnAlias();
- columnAlias.setTableName(tableName.get());
- columnAlias.setColumnName(columnName);
- columnAlias.setTableAlias(tableAlias.getAliasName());
- columnAlias.setColumnAlias(StringFormatter.format("{}.{}", tableAlias.getAliasName(), columnName));
- return columnAlias;
- } catch (ReflectiveOperationException e) {
- throw new TaraException(e);
- }
-
+ });
+ ColumnAlias columnAlias = new ColumnAlias();
+ columnAlias.setTableName(tableName.get());
+ columnAlias.setColumnName(columnName);
+ columnAlias.setTableAlias(tableAlias.getAliasName());
+ columnAlias.setColumnAlias(
+ StringFormatter.format("{}.{}", tableAlias.getAliasName(), columnName));
+ return columnAlias;
+ } catch (ReflectiveOperationException e) {
+ throw new TaraException(e);
}
-
- /**
- * (non-Javadoc)
- * get all relation tables for the query
- *
- * @return Object of table
- */
- @SuppressWarnings("unchecked")
- public static List getTables() {
- LinkedHashMap aliasMap = (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
- return new ArrayList<>(aliasMap.values());
-
+ }
+
+ /**
+ * (non-Javadoc) get all relation tables for the query
+ *
+ * @return Object of table
+ */
+ @SuppressWarnings("unchecked")
+ public static List getTables() {
+ LinkedHashMap aliasMap =
+ (LinkedHashMap) ThreadLocalUtil.get(JOYA_SQL);
+ return new ArrayList<>(aliasMap.values());
+ }
+
+ public static TableStruct getTable(String className) {
+ Optional optional = LocalEntityCache.getInstance().get(className);
+ return optional.orElseThrow(
+ () -> new TaraException("No Table found by className:" + className));
+ }
+
+ /**
+ * 获取数据库中的列明名
+ *
+ * @param column 表别名
+ * @return 列名
+ */
+ public static String getColumnName(String column) {
+
+ if (null == column) {
+ return null;
}
-
- public static TableStruct getTable(String className) {
- Optional optional = LocalEntityCache.getInstance().get(className);
- return optional.orElseThrow(() -> new TaraException("No Table found by className:" + className));
+ int index = column.indexOf(".");
+ if (index < 0) {
+ throw new TaraException("The column is incorrect,it should like 't0.userName.'");
}
-
-
- /**
- * 获取数据库中的列明名
- *
- * @param column 表别名
- * @return 列名
- */
- public static String getColumnName(String column) {
-
- if (null == column) {
- return null;
- }
- int index = column.indexOf(".");
- if (index < 0) {
- throw new TaraException("The column is incorrect,it should like 't0.userName.'");
- }
- String tableAlias = column.substring(0, index);
- String fieldName = column.substring(index + 1);
- String s = null;
- List tables = getTables();
- for (TableAlias table : tables) {
- if (tableAlias.equals(table.getAliasName())) {
- String className = table.getClassName();
- s = LocalEntityCache.getInstance().get(className).map(t -> {
-
- Map fields = t.getFields();
- // if the column is entity field
- if (fields.containsKey(StringUtils.toCamelCase(fieldName))) {
+ String tableAlias = column.substring(0, index);
+ String fieldName = column.substring(index + 1);
+ String s = null;
+ List tables = getTables();
+ for (TableAlias table : tables) {
+ if (tableAlias.equals(table.getAliasName())) {
+ String className = table.getClassName();
+ s =
+ LocalEntityCache.getInstance()
+ .get(className)
+ .map(
+ t -> {
+ Map fields = t.getFields();
+ // if the column is entity field
+ if (fields.containsKey(StringUtils.toCamelCase(fieldName))) {
return fields.get(StringUtils.toCamelCase(fieldName));
- } else {
+ } else {
// if the column is table column
for (String value : fields.values()) {
- if (value.equalsIgnoreCase(StringUtils.toUnderlineCase(fieldName))) {
- return value;
- }
+ if (value.equalsIgnoreCase(StringUtils.toUnderlineCase(fieldName))) {
+ return value;
+ }
}
- }
- throw new TaraException("No column found for table [{}] by name [{}]", table.getTableName(), fieldName);
- }).orElseThrow(() -> new TaraException("No table found by className [{}]", className));
- }
- }
- return StringFormatter.format("{}.{}", tableAlias, s);
+ }
+ throw new TaraException(
+ "No column found for table [{}] by name [{}]",
+ table.getTableName(),
+ fieldName);
+ })
+ .orElseThrow(
+ () -> new TaraException("No table found by className [{}]", className));
+ }
}
-
+ return StringFormatter.format("{}.{}", tableAlias, s);
+ }
}
diff --git a/src/main/java/com/sondertara/joya/cache/LocalEntityCache.java b/src/main/java/com/sondertara/joya/cache/LocalEntityCache.java
index 34c07cd..7605098 100644
--- a/src/main/java/com/sondertara/joya/cache/LocalEntityCache.java
+++ b/src/main/java/com/sondertara/joya/cache/LocalEntityCache.java
@@ -11,80 +11,75 @@
import java.util.List;
import java.util.Optional;
-
/**
* local cache for five min
*
* @author huangxiaohu
*/
-public class LocalEntityCache extends GuavaAbstractLoadingCache implements ILocalCache {
+public class LocalEntityCache extends GuavaAbstractLoadingCache
+ implements ILocalCache {
- private static final Logger log = LoggerFactory.getLogger(LocalEntityCache.class);
+ private static final Logger log = LoggerFactory.getLogger(LocalEntityCache.class);
- private static volatile LocalEntityCache cache = null;
+ private static volatile LocalEntityCache cache = null;
- private LocalEntityCache() {
- setMaximumSize(1000);
- setExpireAfterWriteDuration(60 * 5);
- }
+ private LocalEntityCache() {
+ setMaximumSize(1000);
+ setExpireAfterWriteDuration(60 * 5);
+ }
- private AbstractTableResult tableResult;
+ private AbstractTableResult tableResult;
- public synchronized static LocalEntityCache getInstance() {
+ public static synchronized LocalEntityCache getInstance() {
+ if (null == cache) {
+ synchronized (LocalEntityCache.class) {
if (null == cache) {
- synchronized (LocalEntityCache.class) {
- if (null == cache) {
- cache = new LocalEntityCache();
- cache.setTableResult(new EntityManagerTableResultAdapter());
- }
- }
- }
- return cache;
- }
-
- public void setTableResult(AbstractTableResult tableResult) {
- this.tableResult = tableResult;
- }
-
- @Override
- protected TableStruct fetchData(String key) {
-
- List list = tableResult.load();
- for (TableStruct tableStruct : list) {
- if (tableStruct.getTableName().equalsIgnoreCase(key)) {
- put(tableStruct.getClassName(), tableStruct);
- return tableStruct;
- } else if (tableStruct.getClassName().equalsIgnoreCase(key)) {
- put(tableStruct.getTableName(), tableStruct);
- return tableStruct;
- }
- }
- log.warn("no data to load by key=[{}]", key);
- return null;
-
-
- }
-
- @Override
- public Optional get(String key) {
- TableStruct value = null;
- try {
- value = getValue(key);
- } catch (Exception e) {
- log.error("key={}获取数据异常", key, e);
+ cache = new LocalEntityCache();
+ cache.setTableResult(new EntityManagerTableResultAdapter());
}
- return Optional.ofNullable(value);
+ }
}
-
- @Override
- public void remove(String key) {
- invalidate(key);
-
+ return cache;
+ }
+
+ public void setTableResult(AbstractTableResult tableResult) {
+ this.tableResult = tableResult;
+ }
+
+ @Override
+ protected TableStruct fetchData(String key) {
+
+ List list = tableResult.load();
+ for (TableStruct tableStruct : list) {
+ if (tableStruct.getTableName().equalsIgnoreCase(key)) {
+ put(tableStruct.getClassName(), tableStruct);
+ return tableStruct;
+ } else if (tableStruct.getClassName().equalsIgnoreCase(key)) {
+ put(tableStruct.getTableName(), tableStruct);
+ return tableStruct;
+ }
}
-
-
- public void removeAll() {
- invalidateAll();
-
+ log.warn("no data to load by key=[{}]", key);
+ return null;
+ }
+
+ @Override
+ public Optional get(String key) {
+ TableStruct value = null;
+ try {
+ value = getValue(key);
+ } catch (Exception e) {
+ log.error("key={}获取数据异常", key, e);
}
-}
\ No newline at end of file
+ return Optional.ofNullable(value);
+ }
+
+ @Override
+ public void remove(String key) {
+ invalidate(key);
+ }
+
+ public void removeAll() {
+ invalidateAll();
+ }
+}
diff --git a/src/main/java/com/sondertara/joya/cache/TableClassCache.java b/src/main/java/com/sondertara/joya/cache/TableClassCache.java
index f37ff6a..7823195 100644
--- a/src/main/java/com/sondertara/joya/cache/TableClassCache.java
+++ b/src/main/java/com/sondertara/joya/cache/TableClassCache.java
@@ -26,212 +26,211 @@
/**
* @author skydu
*/
-public class TableClassCache extends GuavaAbstractLoadingCache, Map> implements ILocalCache, Map> {
+public class TableClassCache extends GuavaAbstractLoadingCache, Map>
+ implements ILocalCache, Map> {
- private static volatile TableClassCache cache = null;
-
- private TableClassCache() {
- setMaximumSize(1000);
- setExpireAfterWriteDuration(60 * 60);
- }
+ private static volatile TableClassCache cache = null;
+ private TableClassCache() {
+ setMaximumSize(1000);
+ setExpireAfterWriteDuration(60 * 60);
+ }
- public synchronized static TableClassCache getInstance() {
+ public static synchronized TableClassCache getInstance() {
+ if (null == cache) {
+ synchronized (TableClassCache.class) {
if (null == cache) {
- synchronized (TableClassCache.class) {
- if (null == cache) {
- cache = new TableClassCache();
- }
- }
+ cache = new TableClassCache();
}
- return cache;
+ }
}
-
- /**
- * @return get current classloader
- */
- public static ClassLoader getDefaultClassLoader() {
- ClassLoader cl = null;
+ return cache;
+ }
+
+ /**
+ * @return get current classloader
+ */
+ public static ClassLoader getDefaultClassLoader() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (Throwable ex) {
+ // Cannot access thread context ClassLoader - falling back...
+ }
+ if (cl == null) {
+ // No thread context class loader -> use class loader of this class.
+ cl = TableClassCache.class.getClassLoader();
+ if (cl == null) {
+ // getClassLoader() returning null indicates the bootstrap ClassLoader
try {
- cl = Thread.currentThread().getContextClassLoader();
+ cl = ClassLoader.getSystemClassLoader();
} catch (Throwable ex) {
- // Cannot access thread context ClassLoader - falling back...
+ // Cannot access system ClassLoader - oh well, maybe the caller can live with
+ // null...
}
- if (cl == null) {
- // No thread context class loader -> use class loader of this class.
- cl = TableClassCache.class.getClassLoader();
- if (cl == null) {
- // getClassLoader() returning null indicates the bootstrap ClassLoader
- try {
- cl = ClassLoader.getSystemClassLoader();
- } catch (Throwable ex) {
- // Cannot access system ClassLoader - oh well, maybe the caller can live with
- // null...
- }
- }
- }
- return cl;
+ }
}
-
- /**
- * 获取类的所有字段(包括父类的)
- *
- * @param clazz class
- * @return field
- */
- public static Map getAllFields(Class> clazz) {
- Map fields = Maps.newLinkedHashMap();
- Set filedNames = new HashSet<>();
- for (Class> c = clazz; c != Object.class; c = c.getSuperclass()) {
- try {
- Field[] list = c.getDeclaredFields();
- for (Field field : list) {
- String name = field.getName();
- if (filedNames.contains(name)) {
- continue;
- }
- filedNames.add(field.getName());
- fields.put(field.getName(), field);
- }
- } catch (Exception e) {
- throw new TaraException(e);
- }
+ return cl;
+ }
+
+ /**
+ * 获取类的所有字段(包括父类的)
+ *
+ * @param clazz class
+ * @return field
+ */
+ public static Map getAllFields(Class> clazz) {
+ Map fields = Maps.newLinkedHashMap();
+ Set filedNames = new HashSet<>();
+ for (Class> c = clazz; c != Object.class; c = c.getSuperclass()) {
+ try {
+ Field[] list = c.getDeclaredFields();
+ for (Field field : list) {
+ String name = field.getName();
+ if (filedNames.contains(name)) {
+ continue;
+ }
+ filedNames.add(field.getName());
+ fields.put(field.getName(), field);
}
- return fields;
+ } catch (Exception e) {
+ throw new TaraException(e);
+ }
}
-
-
- /**
- * 获取一个实体类对应数据库字段
- *
- * @param bean java pojo
- * @param the class type of bean
- * @return the table data
- */
- public TableEntity getTable(T bean, boolean readData) {
- Map filedNames = new LinkedHashMap<>();
- Map relation = Maps.newHashMap();
- Class> clazz = bean.getClass();
- Table table = clazz.getAnnotation(Table.class);
- String tableName = null;
- if (null != table) {
- tableName = table.name();
- } else {
- Entity entity = clazz.getAnnotation(Entity.class);
- if (null != entity) {
- tableName = entity.name();
- }
- }
- if (null == tableName) {
- throw new TaraException("No [@Table] or [@Entity] annotation found for class->" + clazz);
- }
- TableEntity tableDTO = new TableEntity();
- tableDTO.setTableName(tableName);
- Optional