Skip to content

Commit

Permalink
Merge pull request #313 from CorvusYe/master
Browse files Browse the repository at this point in the history
When a node has multiple unassociated tags, it supports specifying tag by specifying the resultType
  • Loading branch information
CorvusYe authored Aug 21, 2024
2 parents 836b58b + d330b7c commit 6cc2ced
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 30 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ This source code is licensed under Apache 2.0 License.
- fix: when `use-session-pool` and spaceFromParam is true, skip the space addition.
- fix: when timezone is not default, the time is incorrect.
- fix: allow normal startup without any mapper files.
- fix: Limit the node type obtained by `selectById` to the entity class of the interface.
- fix: When a node has multiple tags, prioritize using the tag of `resultType`. (Collaborate with [charle004](https://github.com/charle004), [#311](https://github.com/nebula-contrib/ngbatis/pull/311))
- fix: debugging log output issue [#312](https://github.com/nebula-contrib/ngbatis/issues/312)

## Feature

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public Object handle(

for (int i = 0; i < columnNames.size(); i++) {
ValueWrapper valueWrapper = record.values().get(i);
Object v = ResultSetUtil.getValue(valueWrapper);
Object v = ResultSetUtil.getValue(valueWrapper, resultType);
newResult = fillResult(v, newResult, columnNames, resultType, i);
}

Expand Down
10 changes: 4 additions & 6 deletions src/main/java/org/nebula/contrib/ngbatis/proxy/MapperProxy.java
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,8 @@ public static ResultSet executeWithParameter(ClassModel cm, MethodModel mm, Stri
try {
localSession = dispatcher.poll();
if (log.isDebugEnabled()) {
StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[6];
proxyClass = stackTraceElement.getClassName();
proxyMethod = stackTraceElement.getMethodName();
proxyClass = cm.getNamespace().getName();
proxyMethod = mm.getId();
localSessionSpace = localSession.getCurrentSpace();
}

Expand Down Expand Up @@ -273,9 +272,8 @@ public static ResultSet executeBySessionPool(ClassModel cm, MethodModel mm, Stri

try {
if (log.isDebugEnabled()) {
StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[6];
proxyClass = stackTraceElement.getClassName();
proxyMethod = stackTraceElement.getMethodName();
proxyClass = cm.getNamespace().getName();
proxyMethod = mm.getId();
}

currentSpace = getSpace(cm, mm, paramsForTemplate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public interface NebulaDaoBasic<T, I extends Serializable> {
*/
default T selectById(@Param("id") I id) {
MethodModel methodModel = getMethodModel();
Class<?> currentType = this.getClass();
Class<?> entityType = entityType(currentType);
methodModel.setResultType(entityType);
ClassModel classModel = getClassModel(this.getClass());
return (T) MapperProxy.invoke(classModel, methodModel, id);
}
Expand Down
97 changes: 95 additions & 2 deletions src/main/java/org/nebula/contrib/ngbatis/utils/ReflectUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.Column;
Expand Down Expand Up @@ -284,18 +287,108 @@ public static Class<?> fieldType(Object o, String fieldName) {
return null;
}


/**
* 判断 parentType 是否是 paramType 或其父类、接口
* @param paramType 待判断类型-子类
* @param parentType 待判断类型-父类或接口
* @return paramType 是否为 parentType 子类或实现类
*/
public static boolean isCurrentTypeOrParentType(Class<?> paramType, Class<?> parentType) {
if (paramType == null) return false;
if (parentType == null) return false;
if (paramType == parentType) {
return true;
}
Set<Class<?>> parentTypes = getParentTypes(paramType);
return parentTypes.contains(parentType);
return parentType.isAssignableFrom(paramType);
}

public static Class<?> findLeafClassFromList(List<Class<?>> list) {
if (list == null || list.isEmpty()) {
return null;
}
Class<?> resultType = list.get(0);
for (int i = 1; i < list.size(); i++) {
Class<?> type = list.get(i);
if (resultType.isAssignableFrom(type)) {
resultType = type;
}
}
return resultType;
}

/**
* 从多个类型中,找到最底层的子类。<br>
* 当 resultType 往深处查找时,如果存在多个子类,返回递归过程未分叉的子类。<br>
* 既根据提供的 tagTypes 集合,查找确定性的运行时类型。<br>
* {@link org.nebula.contrib.ngbatis.utils.ReflectUtilTest#testFindLeafClass()}
*
* @param tagTypes 类型集合
* @param resultType 目标类型
* @return 未分叉的子类
*/
public static Class<?> findNoForkLeafClass(Collection<Class<?>> tagTypes, Class<?> resultType) {
Class<?> nodeType = null;
Map<Class<?>, Set<Class<?>>> classSetMap = extendTree(tagTypes);

Set<Class<?>> subclasses = classSetMap.get(resultType);

// 目标的类,不在标签所对应的类继承树中。
if (subclasses == null) {
return null;
}

// 当目标的类,没有子类,说明已经是子叶节点。
if (subclasses.isEmpty()) {
return resultType;
}

// 当目标的类,有多个子类时,
// 说明在继承树的实现类中存在分歧,程序无法自行决定使用哪个子类。
if (subclasses.size() > 1) {
return resultType;
}

while (subclasses.size() == 1) {
nodeType = subclasses.iterator().next();
subclasses = classSetMap.get(nodeType);
}

return nodeType;
}

/**
* 根据多个类型,生成继承树。
*
* @param tagTypes 类型集合
* @return 继承树
*/
public static Map<Class<?>, Set<Class<?>>> extendTree(Collection<Class<?>> tagTypes) {
Map<Class<?>, Set<Class<?>>> tree = new HashMap<>();
extendTree(tagTypes, tree);
return tree;
}

/**
* 根据多个类型,生成继承树。
*
* @param tagTypes 类型集合
* @param tree 继承树,用于递归的容器
*/
public static void extendTree(Collection<Class<?>> tagTypes, Map<Class<?>, Set<Class<?>>> tree) {
Set<Class<?>> superTypes = new HashSet<>();
for (Class<?> tagType : tagTypes) {
tree.computeIfAbsent(tagType, k -> new HashSet<>());
Class<?> superclass = tagType.getSuperclass();
if (superclass != null) {
Set<Class<?>> children = tree.computeIfAbsent(superclass, k -> new HashSet<>());
children.add(tagType);
superTypes.add(superclass);
}
}
if (!superTypes.isEmpty()) {
extendTree(superTypes, tree);
}
}

/**
Expand Down
49 changes: 28 additions & 21 deletions src/main/java/org/nebula/contrib/ngbatis/utils/ResultSetUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
// This source code is licensed under Apache 2.0 License.

import static org.nebula.contrib.ngbatis.utils.ReflectUtil.castNumber;
import static org.nebula.contrib.ngbatis.utils.ReflectUtil.findLeafClassFromList;
import static org.nebula.contrib.ngbatis.utils.ReflectUtil.findNoForkLeafClass;
import static org.nebula.contrib.ngbatis.utils.ReflectUtil.getPkField;
import static org.nebula.contrib.ngbatis.utils.ReflectUtil.isCurrentTypeOrParentType;
import static org.nebula.contrib.ngbatis.utils.ReflectUtil.schemaByEntityType;

import com.vesoft.nebula.DateTime;
Expand Down Expand Up @@ -79,7 +80,7 @@ public class ResultSetUtil {
* @param <T> 目标结果类型
* @return
*/
public static <T> T getValue(ValueWrapper value) {
public static <T> T getValue(ValueWrapper value, Class<T> resultType) {
try {
Object o = value.isLong() ? value.asLong()
: value.isBoolean() ? value.asBoolean()
Expand All @@ -88,15 +89,17 @@ public static <T> T getValue(ValueWrapper value) {
: value.isTime() ? transformTime(value.asTime())
: value.isDate() ? transformDate(value.asDate())
: value.isDateTime() ? transformDateTime(value.asDateTime())
: value.isVertex() ? transformNode(value.asNode())
: value.isVertex() ? transformNode(value.asNode(), resultType)
: value.isEdge() ? transformRelationship(value)
: value.isPath() ? value.asPath()
: value.isList() ? transformList(value.asList())
: value.isSet() ? transformSet(value.asSet())
: value.isMap() ? transformMap(value.asMap())
: value.isDuration() ? transformDuration(value.asDuration())
: null;

if (o instanceof Number) {
o = castNumber((Number) o, resultType);
}
return (T) o;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
Expand All @@ -106,15 +109,11 @@ public static <T> T getValue(ValueWrapper value) {
/**
* 根据 resultType 从 nebula 的数据类型中获取 java 类型数据
* @param valueWrapper nebula 的数据类型
* @param resultType 接口返回值类型(类型为集合时,为集合泛型)
* @param <T> 调用方用来接收结果的类型,即 resultType
* @return java类型结果
*/
public static <T> T getValue(ValueWrapper valueWrapper, Class<T> resultType) {
T value = getValue(valueWrapper);
if (value instanceof Number) {
value = (T) castNumber((Number) value, resultType);
}
public static <T> T getValue(ValueWrapper valueWrapper) {
T value = getValue(valueWrapper,null);
return value;
}

Expand Down Expand Up @@ -149,26 +148,34 @@ private static Object transformDuration(DurationWrapper du) {
return java.time.Duration.ofNanos(du.getSeconds() * 1000000000);
}

private static Object transformNode(Node node) {
MapperContext mapperContext = MapperProxy.ENV.getMapperContext();
Map<String, Class<?>> tagTypeMapping = mapperContext.getTagTypeMapping();
Class<?> nodeType = null;
private static Object transformNode(Node node, Class<?> resultType) {
List<String> tagNames = node.tagNames();

for (String tagName : tagNames) {
Class<?> tagType = tagTypeMapping.get(tagName);
boolean tagTypeIsSuperClass = isCurrentTypeOrParentType(nodeType, tagType);
if (!tagTypeIsSuperClass) {
nodeType = tagType;
}
}
List<Class<?>> tagTypes = findTagTypes(tagNames);

Class<?> nodeType = resultType == null
? findLeafClassFromList(tagTypes)
: findNoForkLeafClass(tagTypes, resultType);

if (nodeType != null) {
return nodeToResultType(node, nodeType);
}
return if_unknown_node_to_map ? nodeToMap(node) : node;
}

private static List<Class<?>> findTagTypes(List<String> tagNames) {
MapperContext mapperContext = MapperProxy.ENV.getMapperContext();
Map<String, Class<?>> tagTypeMapping = mapperContext.getTagTypeMapping();
List<Class<?>> tagTypes = new ArrayList<>();
for (String tagName : tagNames) {
Class<?> tagType = tagTypeMapping.get(tagName);
if (tagType != null) {
tagTypes.add(tagType);
}
}
return tagTypes;
}

private static Object transformMap(HashMap<String, ValueWrapper> map) {
HashMap<Object, Object> javaResult = new HashMap<>();
for (Map.Entry<String, ValueWrapper> entry : map.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

Expand All @@ -23,4 +25,44 @@ public void testIsCurrentTypeOrParentType() {
Assertions.assertTrue(currentTypeOrParentType);
}

@Test
public void testFindLeafClass() {
Set<Class<?>> classes = new HashSet<Class<?>>() {{
add(A.class);
add(E.class);
add(F.class);
add(G.class);
}};
Class<?> leafType = ReflectUtil.findNoForkLeafClass(classes, C.class);
Assertions.assertEquals(D.class, leafType);

leafType = ReflectUtil.findNoForkLeafClass(classes, E.class);
Assertions.assertEquals(E.class, leafType);

leafType = ReflectUtil.findNoForkLeafClass(classes, B.class);
Assertions.assertEquals(B.class, leafType);
}
}

/*
* - A
* - B
* - C
* - D
* - F
* - G
* - E
*/
class A {}

class B extends A {}

class C extends B {}

class D extends C {}

class F extends D {}

class G extends D {}

class E extends B {}

0 comments on commit 6cc2ced

Please sign in to comment.