/**
* 插入数据之前设置id ,create_time
*
* @return id
*/
private String preInsert(T entity) throws ReflectiveOperationException {
Method getIdMethod = null;
Method setTimeMethod = null;
Method setCreateUserMethod = null;
Method getTimeMethod = null;
Method getCreateUserMethod = null;
Class<?> entityClass = getEntityClass();
String setKeyMethodName = "setId";
String getKeyMethodName = "getId";
try {
getIdMethod = entityClass.getMethod(getKeyMethodName);//写成id,如果数据库字段不是id,走catch
} catch (NoSuchMethodException e) {
Field field = getKeyField(entityClass);//找到主键
if (field != null) {
String fieldName = field.getName();//主键的属性,例如 userId
String upperCase = upperCase(fieldName); //主键的属性的首字母转大写
getKeyMethodName = "get" + upperCase;
setKeyMethodName = "set" + upperCase;
getIdMethod = entityClass.getMethod(getKeyMethodName);
}
}
try {
getTimeMethod = entityClass.getMethod("getCreateTime");//创建时间
Object createTime = getTimeMethod.invoke(entity);
if (createTime == null) {
setTimeMethod = entityClass.getMethod("setCreateTime", Date.class);//类型是date类型,所以是date.class
setTimeMethod.invoke(entity, new Date());//赛入值
}
} catch (NoSuchMethodException e) {
logger.warn("preInsert————获取或设置创建时间异常", e.getMessage());
}
try {
getCreateUserMethod = entityClass.getMethod("getCreateUser");
String userId = (String) getCreateUserMethod.invoke(entity);
if (StringUtils.isBlank(userId)) {
setCreateUserMethod = entityClass.getMethod("setCreateUser", String.class);
UserLine user =null;
try {
user= ShiroUtils.getUserLine();//从shiro中那的,可根据自己业务逻辑修改
}catch (Exception e){
logger.warn("无序登录业务处理");
}
if (user != null) {//已经登陆
setCreateUserMethod.invoke(entity, user.getId());
}
}
} catch (NoSuchMethodException e) {
logger.warn("preInsert————获取或设置创建用户异常", e.getMessage());
}
String id = null;
if (getIdMethod != null) {
id = (String) getIdMethod.invoke(entity);
if (StringUtils.isEmpty(id)) {
Method setIdMethod = entityClass.getMethod(setKeyMethodName, String.class);
id = sid.nextShort();//方法生成的id,可自行修改,此处不贴具体id生成策略了,
setIdMethod.invoke(entity, id);
}
}
return id;//生成的id返回
}
/**
* 获取实体类主键属性字段,根据Id注解进行区分
* 只对单Id注解有效,对于无Id注解或多Id注解,返回null
*
* @param clazz clazz
* @return 属性
*/
private Field getKeyField(Class<?> clazz) {
Field[] declaredFields = clazz.getDeclaredFields();
List fields = new ArrayList<>();
for (Field field : declaredFields) {
Id declaredAnnotation = field.getAnnotation(Id.class);
if (declaredAnnotation != null) {
fields.add(field);
}
}
return fields.size() != 1 ? null : fields.get(0);
}
private String upperCase(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
}