先自定义两个注解:@TableTreeParentId、@TableTreePath
@TableTreeParentId.png @TableTreePath.png
实体类中使用
image.png比如新增一个机构:/api/org/insert
service里重写insert 方法
@Override
public boolean insert(T entity) {
try {
setPath(entity);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return super.insert(entity);
}
setPath方法
protected void setPath(T model) throws IllegalAccessException {
Map<Class, Field> annoFieldMap = getAnnoNameAndValue(model.getClass());
Field tableTreePathField = annoFieldMap.get(TableTreePath.class);
Field tableTreeParentIdField = annoFieldMap.get(TableTreeParentId.class);
tableTreePathField.setAccessible(true);
tableTreeParentIdField.setAccessible(true);
Serializable parentId = ((Serializable) tableTreeParentIdField.get(model));
if(parentId != null) {
//最顶层 则PATH设置为/
if (parentId.toString().equals("0") || StringUtils.isEmpty(parentId.toString())) {
tableTreePathField.set(model, "/");
} else {
T parent = this.selectById(parentId);
String parentPath = tableTreePathField.get(parent).toString();
String modelPath = parentPath + parentId.toString() + "/";
tableTreePathField.set(model, modelPath);
}
}
}
getAnnoNameAndValue方法
利用反射机制得到该类的所有属性(private、default、protected、public),java.lang.Class.getAnnotations()
方法返回当前这个元素上的所有注释。如果这个元素没有注释,它返回一个长度为零的数组。
protected Map<Class, Field> getAnnoNameAndValue(Class clazz) {
Map<Class, Field> result = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
Class<? extends Annotation> annoClass = annotation.annotationType();
result.put(annoClass, field);
}
}
return result;
}
网友评论