MySQL表字段设置默认值的两种方法
在java代码中给mysql必备字段设置默认值
第一种方式
mybatisplus提供的@TableField注解直接可以解决时间默认值的问题
(图片来源网络,侵删)
@TableField注解配合FieldFill 根据新增修改不同操作设置默认值
// 字段添加填充内容 @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必备字段赋值
比第一种方式的好处是可以根据项目的权限控制,获取当前登录人信息,记录当前登录人为操作人
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 void setFieldValueWhenExists(T t, String fieldName, Object value) { setFieldValueWhenExists(t, fieldName, value, false); } public static void setFieldValue(T t, String fieldName, Object value) { setFieldValueWhenExists(t, fieldName, value, true); } public static void setFieldValueWhenExists(T t, String fieldName, Object value, boolean override) { try { List 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 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 getField(Class clazz, String filedName) { if (clazz != null && !StringUtils.isEmpty(filedName)) { List 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 getFieldByName(List fields, String fieldName) { if (fields != null && fields.size() != 0 && !StringUtils.isEmpty(fieldName)) { List 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); } }
自定义类,重写相关方法,设置默认值
public abstract class BaseService extends ServiceImpl { 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); } }
项目中统一继承BaseService类即可
@Slf4j @Service public class UserServiceImpl extends BaseService { }
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。