在java代码中给mysql必备字段设置默认值
第一种方式
mybatisplus提供的@TableField注解直接可以解决时间默认值的问题
@TableField注解配合FieldFill 根据新增修改不同操作设置默认值
java
// 字段添加填充内容
@ApiModelProperty(value = "创建时间")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "create_date", fill = FieldFill.INSERT)
private LocalDateTime createDate;
@ApiModelProperty(value = "修改时间")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "modify_date", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime modifyDate;
第二种方式
自定义反射工具类ReflectUtil,统一处理mysql必备字段赋值
java
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
public class ReflectUtil {
private static final Logger log = LoggerFactory.getLogger(ReflectUtil.class);
private ReflectUtil() {
}
public static <T> void setFieldValueWhenExists(T t, String fieldName, Object value) {
setFieldValueWhenExists(t, fieldName, value, false);
}
public static <T> void setFieldValue(T t, String fieldName, Object value) {
setFieldValueWhenExists(t, fieldName, value, true);
}
public static <T> void setFieldValueWhenExists(T t, String fieldName, Object value, boolean override) {
try {
List<Field> fields = getField(t.getClass(), fieldName);
if (CollectionUtils.isEmpty(fields)) {
return;
}
Iterator var5 = fields.iterator();
while(var5.hasNext()) {
Field field = (Field)var5.next();
setSingleFieldValue(t, field, fieldName, value, override);
}
} catch (Exception var7) {
log.error("反射设置属性值失败", var7);
}
}
private static <T> void setSingleFieldValue(T t, Field field, String fieldName, Object value, boolean override) throws Exception {
int typeCode = field.getModifiers();
Object oldValue = null;
Method method;
if (Modifier.isPublic(typeCode)) {
oldValue = field.get(t);
} else {
method = t.getClass().getMethod("get" + getMethodName(fieldName));
oldValue = method.invoke(t);
}
if (oldValue == null || override) {
if (Modifier.isPublic(typeCode)) {
field.set(t, value);
} else {
method = t.getClass().getMethod("set" + getMethodName(fieldName), value != null ? value.getClass() : field.getType());
method.invoke(t, value);
}
}
}
private static String getMethodName(String fieldName) throws Exception {
byte[] items = fieldName.getBytes();
items[0] = (byte)((char)items[0] - 97 + 65);
return new String(items);
}
public static List<Field> getField(Class<?> clazz, String filedName) {
if (clazz != null && !StringUtils.isEmpty(filedName)) {
List<Field> fields = new ArrayList();
for(Class<?> tempClass = clazz; tempClass != null; tempClass = tempClass.getSuperclass()) {
fields.addAll(Arrays.asList(tempClass.getDeclaredFields()));
}
return (List)(CollectionUtils.isEmpty(fields) ? fields : getFieldByName(fields, filedName));
} else {
throw new IllegalArgumentException("params is illegal");
}
}
public static List<Field> getFieldByName(List<Field> fields, String fieldName) {
if (fields != null && fields.size() != 0 && !StringUtils.isEmpty(fieldName)) {
List<Field> foundFields = new ArrayList();
Iterator var3 = fields.iterator();
while(var3.hasNext()) {
Field field = (Field)var3.next();
String name = field.getName();
if (fieldName.equals(name)) {
foundFields.add(field);
}
}
return foundFields;
} else {
throw new IllegalArgumentException("params is illegal");
}
}
public static boolean isFiledWithName(Field field, String fieldName) {
if (field != null && !StringUtils.isEmpty(fieldName)) {
return fieldName.equals(field.getName());
} else {
throw new IllegalArgumentException("params is illegal");
}
}
public static String getFieldValueByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object hisValue = field.get(object);
return null == hisValue ? "" : hisValue.toString();
} catch (Exception var4) {
return "";
}
}
public static Object getFieldValue(Object obj, String fieldName, boolean isTrimSpace) {
Object val = null;
if (obj instanceof Map) {
val = ((Map)obj).get(fieldName);
} else {
val = getProperty(obj, fieldName);
}
if (val != null && val instanceof String && isTrimSpace) {
val = ((String)val).trim();
if ("".equals(val)) {
val = null;
}
}
return val;
}
private static Object getProperty(Object obj, String fieldName) {
PropertyDescriptor pd = getPropertyDescriptor(obj.getClass(), fieldName);
if (pd != null && pd.getReadMethod() != null) {
try {
return pd.getReadMethod().invoke(obj, (Object[])null);
} catch (Exception var4) {
throw new RuntimeException(var4);
}
} else {
throw new IllegalStateException("In class" + obj.getClass() + ", no getter method found for field '" + fieldName + "'");
}
}
private static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName) {
return BeanUtils.getPropertyDescriptor(clazz, propertyName);
}
}
自定义类,重写相关方法,设置默认值
java
public abstract class BaseService<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {
protected Log log = LogFactory.getLog(this.getClass());
@Autowired
protected M baseMapper;
public boolean save(T entity) {
this.beforeSave(entity);
return super.save(entity);
}
public boolean updateById(T entity) {
this.beforeUpdate(entity);
return super.updateById(entity);
}
public boolean auditById(T entity) {
this.beforeAudit(entity);
return super.updateById(entity);
}
protected void beforeSave(Object object) {
LocalDateTime now = LocalDateTime.now();
// 可根据项目中具体情况获取当前登录信息
String userLogin = "admin";
ReflectUtil.setFieldValue(object, "createBy", userLogin);
ReflectUtil.setFieldValue(object, "createDate", now);
ReflectUtil.setFieldValue(object, "modifyBy", userLogin);
ReflectUtil.setFieldValue(object, "modifyDate", now);
}
protected void beforeUpdate(Object object) {
LocalDateTime now = LocalDateTime.now();
String userLogin = "admin";
ReflectUtil.setFieldValue(object, "modifyBy", userLogin);
ReflectUtil.setFieldValue(object, "modifyDate", now);
}
protected void beforeAudit(Object object) {
LocalDateTime now = LocalDateTime.now();
String userLogin = "admin";
ReflectUtil.setFieldValue(object, "auditBy", userLogin);
ReflectUtil.setFieldValue(object, "auditDate", now);
}
}