All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.tool.datebase.jpa.AbsJpaDataAutoFill Maven / Gradle / Ivy

There is a newer version: 1.3.2
Show newest version
package top.doudou.common.tool.datebase.jpa;

import lombok.extern.slf4j.Slf4j;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * @Description jap数据填充
 *   需要在数据库的实体类上加 @EntityListeners注解,并将配置的填充类复制给注解的value
 * @Author 傻男人 <[email protected]>
 * @Date 2020-10-15 11:17
 * @Version V1.0
 */
@Slf4j
public abstract class AbsJpaDataAutoFill {

    /**
     * 新增数据时,自动填充
     * 需要在方法上添加@PrePersist注解
     * @param object
     */
    @PrePersist
    public abstract void prePersist(Object object);

    /**
     * 更新数据时,自动填充
     * 需要在方法上添加@PreUpdate注解
     * @param object
     */
    @PreUpdate
    public abstract void preUpdate(Object object);


    /**
     * 填充属性
     * @param object
     * @param propertyName  属性名
     * @param value 属性对应的值
     */
    public void setProperty(Object object,String propertyName,Object value) {
        try {
            Class aClass = object.getClass();
            Field field = aClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            Object objValue = field.get(object);
            if (objValue == null) {
                field.set(object, value);
            }
        }catch (Exception e){
            log.error("jpa自动填充失败,实体为:{},属性:{},默认值为:{},错误的原因为:{}",object,propertyName,value,e.getMessage());
        }
    }

    /**
     * 更新时间属性
     * @param object
     * @param propertyName
     */
    public void updateTime(Object object,String propertyName) {
        try {
            Class aClass = object.getClass();
            Field field = aClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            field.set(object, new Date());
        }catch (Exception e){
            log.error("jpa自动填充时间失败,实体为:{},属性:{},错误的原因为:{}",object,propertyName,e.getMessage());
        }
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy