rename UpdateEntity.wrap to UpdateEntity.of; close #I6Z7HK

This commit is contained in:
开源海哥 2023-04-28 07:53:12 +08:00
parent 61bfc6fb5d
commit d31d36887e

View File

@ -16,26 +16,69 @@
package com.mybatisflex.core.util;
import com.mybatisflex.core.javassist.ModifyAttrsRecordProxyFactory;
import com.mybatisflex.core.table.IdInfo;
import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.Reflector;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.invoker.Invoker;
import java.lang.reflect.Array;
import java.util.List;
public class UpdateEntity {
private static ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
public static <T> T wrap(Class<T> clazz) {
public static <T> T of(Class<T> clazz) {
return ModifyAttrsRecordProxyFactory.getInstance().get(clazz);
}
public static <T> T of(Class<T> clazz, Object id) {
T newEntity = ModifyAttrsRecordProxyFactory.getInstance().get(clazz);
TableInfo tableInfo = TableInfoFactory.ofEntityClass(clazz);
List<IdInfo> primaryKeyList = tableInfo.getPrimaryKeyList();
Reflector reflector = reflectorFactory.findForClass(clazz);
if (primaryKeyList != null && !primaryKeyList.isEmpty()) {
for (int i = 0; i < primaryKeyList.size(); i++) {
IdInfo idInfo = primaryKeyList.get(i);
Object idValue = getIdValue(id, i);
Invoker setInvoker = reflector.getSetInvoker(idInfo.getProperty());
try {
setInvoker.invoke(newEntity, new Object[]{ConvertUtil.convert(idValue, idInfo.getPropertyType())});
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
return newEntity;
}
private static Object getIdValue(Object id, int index) {
if (id == null) {
return null;
}
if (ClassUtil.isArray(id.getClass())) {
if (index >= Array.getLength(id)) {
return null;
} else {
return Array.get(id, index);
}
}
//not array
return index == 0 ? id : null;
}
public static <T> T ofNotNull(T entity) {
Class<?> usefulClass = ClassUtil.getUsefulClass(entity.getClass());
T newEntity = (T) wrap(usefulClass);
T newEntity = (T) of(usefulClass);
Reflector reflector = reflectorFactory.findForClass(usefulClass);
String[] propertyNames = reflector.getGetablePropertyNames();
@ -48,7 +91,7 @@ public class UpdateEntity {
reflector.getSetInvoker(propertyName).invoke(newEntity, new Object[]{value});
}
} catch (Exception e) {
//ignore();
//ignore;
}
}