最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot自定義注解解決公共字段填充問題解決

 更新時間:2024年07月03日 11:09:23   作者:今天的接口寫完了嗎?  
修改時間,修改人等字段時,這些字段屬于公共字段,本文主要介紹了SpringBoot自定義注解解決公共字段填充問題解決,使用它的好處就是可以統(tǒng)一對這些字段進行處理,感興趣的可以了解一下

1 問題分析

新增員工或者新增菜品分類時需要設置創(chuàng)建時間、創(chuàng)建人、修改時間、修改人等字段,在編輯員工或者編輯菜品分類時需要設置修改時間、修改人等字段。這些字段屬于公共字段,也就是也就是在我們的系統(tǒng)中很多表中都會有這些字段,如下:

序號字段名含義數(shù)據(jù)類型
1create_time創(chuàng)建時間datetime
2create_user創(chuàng)建人idbigint
3update_time修改時間datetime
4update_user修改人idbigint

而針對于這些字段,我們的賦值方式為:

1). 在新增數(shù)據(jù)時, 將createTime、updateTime 設置為當前時間, createUser、updateUser設置為當前登錄用戶ID。

2). 在更新數(shù)據(jù)時, 將updateTime 設置為當前時間, updateUser設置為當前登錄用戶ID。

目前,在我們的項目中處理這些字段都是在每一個業(yè)務方法中進行賦值操作,如下:

新增員工方法:

	/**
     * 新增員工
     *
     * @param employeeDTO
     */
    public void save(EmployeeDTO employeeDTO) {
        //.......................
		//
        //設置當前記錄的創(chuàng)建時間和修改時間
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //設置當前記錄創(chuàng)建人id和修改人id
        employee.setCreateUser(BaseContext.getCurrentId());//目前寫個假數(shù)據(jù),后期修改
        employee.setUpdateUser(BaseContext.getCurrentId());
		///
        employeeMapper.insert(employee);
    }

編輯員工方法:

	/**
     * 編輯員工信息
     *
     * @param employeeDTO
     */
    public void update(EmployeeDTO employeeDTO) {
       //........................................
	   ///
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
       ///

        employeeMapper.update(employee);
    }

新增菜品分類方法:

	/**
     * 新增分類
     * @param categoryDTO
     */
    public void save(CategoryDTO categoryDTO) {
       //....................................
       //
        //設置創(chuàng)建時間、修改時間、創(chuàng)建人、修改人
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        ///

        categoryMapper.insert(category);
    }

修改菜品分類方法:

	/**
     * 修改分類
     * @param categoryDTO
     */
    public void update(CategoryDTO categoryDTO) {
        //....................................
        
		//
        //設置修改時間、修改人
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());
        //

        categoryMapper.update(category);
    }

如果都按照上述的操作方式來處理這些公共字段, 需要在每一個業(yè)務方法中進行操作, 編碼相對冗余、繁瑣,那能不能對于這些公共字段在某個地方統(tǒng)一處理,來簡化開發(fā)呢?

答案是可以的,我們使用AOP切面編程,實現(xiàn)功能增強,來完成公共字段自動填充功能。

2 實現(xiàn)思路

在實現(xiàn)公共字段自動填充,也就是在插入或者更新的時候為指定字段賦予指定的值,使用它的好處就是可以統(tǒng)一對這些字段進行處理,避免了重復代碼。在上述的問題分析中,我們提到有四個公共字段,需要在新增/更新中進行賦值操作, 具體情況如下:

序號字段名含義數(shù)據(jù)類型操作類型
1create_time創(chuàng)建時間datetimeinsert
2create_user創(chuàng)建人idbigintinsert
3update_time修改時間datetimeinsert、update
4update_user修改人idbigintinsert、update

實現(xiàn)步驟:

1). 自定義注解 AutoFill,用于標識需要進行公共字段自動填充的方法

2). 自定義切面類 AutoFillAspect,統(tǒng)一攔截加入了 AutoFill 注解的方法,通過反射為公共字段賦值

3). 在 Mapper 的方法上加入 AutoFill 注解

若要實現(xiàn)上述步驟,需掌握以下知識(之前課程內(nèi)容都學過)

**技術(shù)點:**枚舉、注解、AOP、反射

3 代碼開發(fā)

按照上一小節(jié)分析的實現(xiàn)步驟依次實現(xiàn),共三步。

3.1 步驟一

自定義注解 AutoFill

進入到sky-server模塊,創(chuàng)建com.sky.annotation包。

package com.sky.annotation;

import com.sky.enumeration.OperationType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定義注解,用于標識某個方法需要進行功能字段自動填充處理
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    //數(shù)據(jù)庫操作類型:UPDATE INSERT
    OperationType value();
}

其中OperationType已在sky-common模塊中定義

package com.sky.enumeration;

/**
 * 數(shù)據(jù)庫操作類型
 */
public enum OperationType {

    /**
     * 更新操作
     */
    UPDATE,

    /**
     * 插入操作
     */
    INSERT
}

3.2 步驟二

自定義切面 AutoFillAspect

在sky-server模塊,創(chuàng)建com.sky.aspect包。

package com.sky.aspect;

/**
 * 自定義切面,實現(xiàn)公共字段自動填充處理邏輯
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 切入點
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    /**
     * 前置通知,在通知中進行公共字段的賦值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        /重要
        //可先進行調(diào)試,是否能進入該方法 提前在mapper方法添加AutoFill注解
        log.info("開始進行公共字段自動填充...");

    }
}

完善自定義切面 AutoFillAspect 的 autoFill 方法

package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定義切面,實現(xiàn)公共字段自動填充處理邏輯
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 切入點
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    /**
     * 前置通知,在通知中進行公共字段的賦值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("開始進行公共字段自動填充...");

        //獲取到當前被攔截的方法上的數(shù)據(jù)庫操作類型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法簽名對象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//獲得方法上的注解對象
        OperationType operationType = autoFill.value();//獲得數(shù)據(jù)庫操作類型

        //獲取到當前被攔截的方法的參數(shù)--實體對象
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }

        Object entity = args[0];

        //準備賦值的數(shù)據(jù)
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //根據(jù)當前不同的操作類型,為對應的屬性通過反射來賦值
        if(operationType == OperationType.INSERT){
            //為4個公共字段賦值
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //通過反射為對象屬性賦值
                setCreateTime.invoke(entity,now);
                setCreateUser.invoke(entity,currentId);
                setUpdateTime.invoke(entity,now);
                setUpdateUser.invoke(entity,currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(operationType == OperationType.UPDATE){
            //為2個公共字段賦值
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //通過反射為對象屬性賦值
                setUpdateTime.invoke(entity,now);
                setUpdateUser.invoke(entity,currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

3.3 步驟三

在Mapper接口的方法上加入 AutoFill 注解

CategoryMapper為例,分別在新增和修改方法添加@AutoFill()注解,也需要EmployeeMapper做相同操作

package com.sky.mapper;

@Mapper
public interface CategoryMapper {
    /**
     * 插入數(shù)據(jù)
     * @param category
     */
    @Insert("insert into category(type, name, sort, status, create_time, update_time, create_user, update_user)" +
            " VALUES" +
            " (#{type}, #{name}, #{sort}, #{status}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser})")
    @AutoFill(value = OperationType.INSERT)
    void insert(Category category);
    /**
     * 根據(jù)id修改分類
     * @param category
     */
    @AutoFill(value = OperationType.UPDATE)
    void update(Category category);

}

同時,將業(yè)務層為公共字段賦值的代碼注釋掉。

1). 將員工管理的新增和編輯方法中的公共字段賦值的代碼注釋。

2). 將菜品分類管理的新增和修改方法中的公共字段賦值的代碼注釋。

到此這篇關(guān)于SpringBoot自定義注解解決公共字段填充問題解決的文章就介紹到這了,更多相關(guān)SpringBoot 公共字段填充內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java中歸并排序和Master公式詳解

    java中歸并排序和Master公式詳解

    大家好,本篇文章主要講的是java中歸并排序和Master公式詳解,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • 解析WeakHashMap與HashMap的區(qū)別詳解

    解析WeakHashMap與HashMap的區(qū)別詳解

    本篇文章是對WeakHashMap與HashMap的區(qū)別進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • jpa實體@ManyToOne @OneToMany無限遞歸方式

    jpa實體@ManyToOne @OneToMany無限遞歸方式

    這篇文章主要介紹了jpa實體@ManyToOne @OneToMany無限遞歸方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • MyBatis discriminator標簽原理實例解析

    MyBatis discriminator標簽原理實例解析

    這篇文章主要為大家介紹了MyBatis discriminator標簽實現(xiàn)原理實例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • Kotlin null的處理詳解

    Kotlin null的處理詳解

    這篇文章主要介紹了Kotlin null的處理詳解的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • java8新特性之接口的static和default的使用

    java8新特性之接口的static和default的使用

    這篇文章主要介紹了java8新特性之接口的static和default的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-01-01
  • springboot項目部署到寶塔的詳細圖文教程

    springboot項目部署到寶塔的詳細圖文教程

    網(wǎng)上關(guān)于寶塔運行springBoot的東西說有點迷糊,但是有一句話很重要,Spring boot項目只需要JDK環(huán)境即可部署成功,下面這篇文章主要給大家介紹了關(guān)于springboot項目部署到寶塔的詳細圖文教程,需要的朋友可以參考下
    2023-05-05
  • SpringBoot之bootstrap和application的區(qū)別解讀

    SpringBoot之bootstrap和application的區(qū)別解讀

    這篇文章主要介紹了SpringBoot之bootstrap和application的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • 詳解Javaee Dao層的抽取

    詳解Javaee Dao層的抽取

    這篇文章主要介紹了詳解Javaee Dao層的抽取,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • java中Map如何根據(jù)key的大小進行排序詳解

    java中Map如何根據(jù)key的大小進行排序詳解

    這篇文章主要給大家介紹了關(guān)于java中Map如何根據(jù)key的大小進行排序的相關(guān)資料,有時候我們業(yè)務上需要對map里面的值按照key的大小來進行排序的時候我們就可以利用如下方法來進行排序了,需要的朋友可以參考下
    2023-09-09

最新評論

随州市| 甘德县| 广东省| 滨海县| 城固县| 巍山| 塔河县| 郁南县| 德庆县| 石嘴山市| 平湖市| 山东省| 大兴区| 稷山县| 丰宁| 雷波县| 错那县| 运城市| 滦平县| 宣威市| 石首市| 霍邱县| 北川| 广平县| 昂仁县| 毕节市| 新乡县| 湾仔区| 清涧县| 南安市| 丁青县| 大邑县| 桦南县| 台江县| 江阴市| 丘北县| 徐闻县| 清徐县| 五莲县| 聂拉木县| 灌阳县|