com.hecloud.runtime.database.utils.EntityBuilder Maven / Gradle / Ivy
package com.hecloud.runtime.database.utils;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author LoveInBJ-1024
*/
@Slf4j
@Data
@Builder
public class EntityBuilder {
private final static String CREATE = "gmtCreate";
private final static String MODIFY = "gmtModify";
private final static String DELETE = "deleted";
/**
* 处理保存前的字段赋值
*
* @param target 需要处理实体对象
*/
public void beforeInsert(Object target) {
try {
if (contains(target.getClass(), CREATE)) {
Method setGmtCreateMethod = target.getClass().getMethod("setGmtCreate", Date.class);
setGmtCreateMethod.invoke(target, new Date());
}
if (contains(target.getClass(), MODIFY)) {
Method setGmtModifyMethod = target.getClass().getMethod("setGmtModify", Date.class);
setGmtModifyMethod.invoke(target, new Date());
}
if (contains(target.getClass(), DELETE)) {
Method setDeletedMethod = target.getClass().getMethod("setDeleted", Boolean.class);
setDeletedMethod.invoke(target, false);
}
} catch (Exception e) {
log.error("before create method processing occur exception!", e);
}
}
/**
* 处理更新前的字段赋值
*
* @param target 需要处理实体对象
*/
public void beforeUpdate(Object target) {
try {
if (contains(target.getClass(), MODIFY)) {
Method setGmtModifyMethod = target.getClass().getMethod("setGmtModify", Date.class);
setGmtModifyMethod.invoke(target, new Date());
}
} catch (Exception e) {
log.error("before modify method processing occur exception!", e);
}
}
/**
* 类中是否存在某属性
*
* @param clazz 类名
* @param field 属性
* @return 是否存在
*/
private boolean contains(Class clazz, String field) {
Field[] fields = clazz.getDeclaredFields();
Field[] parent = Optional.of(clazz.getSuperclass().getDeclaredFields()).orElse(new Field[0]);
List fieldNames = new ArrayList<>();
Arrays.stream(fields).forEach(f -> fieldNames.add(f.getName()));
Arrays.stream(parent).forEach(f -> fieldNames.add(f.getName()));
return fieldNames.contains(field);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy