MySQL表字段设置默认值的两种方法

在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);
    }
}
相关推荐
C吴新科1 小时前
MySQL入门操作详解
mysql
魔道不误砍柴功1 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
NiNg_1_2341 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
闲晨1 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
测开小菜鸟2 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
Ai 编码助手3 小时前
MySQL中distinct与group by之间的性能进行比较
数据库·mysql
P.H. Infinity3 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天3 小时前
java的threadlocal为何内存泄漏
java
陈燚_重生之又为程序员4 小时前
基于梧桐数据库的实时数据分析解决方案
数据库·数据挖掘·数据分析
caridle4 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express