亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Mybatis攔截器實(shí)現(xiàn)公共字段填充的示例代碼

 更新時(shí)間:2024年12月12日 10:12:27   作者:WuWuII  
本文介紹了使用Spring Boot和MyBatis實(shí)現(xiàn)公共字段的自動(dòng)填充功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

說(shuō)明

基于springBoot+mybatis,三步完成

  • 編寫(xiě)注解,然后將注解放在對(duì)應(yīng)的想要填充的字段上
  • 編寫(xiě)攔截器
  • 注冊(cè)攔截器

注解

AutoId

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AutoId {
    IdType type() default IdType.SNOWFLAKE;
    enum IdType{
        UUID,
        SNOWFLAKE,
    }
}

CreateTime

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CreateTime {
    String value() default "";
}

UpdateTime

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface UpdateTime {
    String value() default "";
}

Mybatis攔截器

根據(jù)實(shí)體來(lái)選一種就行

實(shí)體沒(méi)有父類的情況

import cn.hutool.core.util.IdUtil;
import com.example.mybatisinterceptor.annotation.AutoId;
import com.example.mybatisinterceptor.annotation.CreateTime;
import com.example.mybatisinterceptor.annotation.UpdateTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * Mybatis攔截器實(shí)現(xiàn)類,用于在插入或更新操作中自動(dòng)處理創(chuàng)建時(shí)間、更新時(shí)間和自增ID。
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    /**
     * 對(duì)執(zhí)行的SQL命令進(jìn)行攔截處理。
     * 
     * @param invocation 攔截器調(diào)用對(duì)象,包含方法參數(shù)和目標(biāo)對(duì)象等信息。
     * @return 繼續(xù)執(zhí)行目標(biāo)方法后的返回結(jié)果。
     * @throws Throwable 方法執(zhí)行可能拋出的異常。
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
            Object parameter = invocation.getArgs()[1];
            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                Object obj = map.get("list");
                List<?> list = (List<?>) obj;
                if (list != null) {
                    for (Object o : list) {
                        setParameter(o, sqlCommandType);
                    }
                }
            } else {
                setParameter(parameter, sqlCommandType);
            }
        }
        return invocation.proceed();
    }

    /**
     * 設(shè)置參數(shù)的創(chuàng)建時(shí)間和更新時(shí)間,以及自增ID。
     * 
     * @param parameter 待處理的參數(shù)對(duì)象。
     * @param sqlCommandType SQL命令類型,用于區(qū)分插入還是更新操作。
     * @throws Throwable 設(shè)置字段值可能拋出的異常。
     */
    public void setParameter(Object parameter, SqlCommandType sqlCommandType) throws Throwable {
        Class<?> aClass = parameter.getClass();
        Field[] declaredFields;
        declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            LocalDateTime now = LocalDateTime.now();
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                if (field.getAnnotation(CreateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                if (field.getAnnotation(AutoId.class) != null ) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.SNOWFLAKE)) {
                            field.set(parameter, IdUtil.getSnowflakeNextId());
                        } else if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.UUID)) {
                            field.set(parameter, IdUtil.simpleUUID());
                        }
                    }
                }
            }
            if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
        }
    }

    /**
     * 給目標(biāo)對(duì)象創(chuàng)建一個(gè)代理。
     * 
     * @param target 目標(biāo)對(duì)象,即被攔截的對(duì)象。
     * @return 返回目標(biāo)對(duì)象的代理對(duì)象。
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}

實(shí)體有父類的情況

package com.kd.center.service.user.interceptor;

import cn.hutool.core.util.IdUtil;
import com.kd.common.annotation.AutoId;
import com.kd.common.annotation.CreateTime;
import com.kd.common.annotation.UpdateTime;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Component
//method = "update"攔截修改操作,包括新增
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
    	//MappedStatement包括方法名和要操作的參數(shù)值
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        //sql語(yǔ)句的類型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //判斷是不是插入或者修改
        if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
        	//獲取參數(shù)
            Object parameter = invocation.getArgs()[1];
            //是不是鍵值對(duì)
            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                Object obj = map.get("list");
                List<?> list = (List<?>) obj;
                if (list != null) {
                    for (Object o : list) {
                        setParameter(o, sqlCommandType);
                    }
                }
            } else {
            	//設(shè)置值
                setParameter(parameter, sqlCommandType);
            }
        }
        return invocation.proceed();
    }

    /**
     * 設(shè)置值
     * @param parameter     sql中對(duì)象的值
     * @param sqlCommandType        sql執(zhí)行類型
     * @throws Throwable
     */
    public void setParameter(Object parameter, SqlCommandType sqlCommandType) throws Throwable {
    	//獲取對(duì)象class
        Class<?> aClass = parameter.getClass();
        //獲取所有屬性
        Field[] declaredFields;
        declaredFields = aClass.getDeclaredFields();
        //遍歷屬性
        for (Field field : declaredFields) {
        	//如果是插入語(yǔ)句
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
            	//獲取屬性的注解,如果注解是@AutoId,代表它是id
                if (field.getAnnotation(AutoId.class) != null ) {
                	//繞過(guò)檢查
                    field.setAccessible(true);
                    //如果值是空的
                    if (field.get(parameter) == null) {
                    	//如果是雪花算法,就按照雪花算法生成主鍵id,替換參數(shù)的id
                        if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.SNOWFLAKE)) {
                            field.set(parameter, IdUtil.getSnowflakeNextId());
                        } else if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.UUID)) {	//否則生成簡(jiǎn)單id,替換參數(shù)的id
                            field.set(parameter, IdUtil.simpleUUID());
                        }
                    }
                }
            }
        }
		//如果是繼承了基類,創(chuàng)建時(shí)間和修改時(shí)間都在基類中,先獲取基類class
        Class<?> superclass = aClass.getSuperclass();
        //獲取所有屬性
        Field[] superclassFields = superclass.getDeclaredFields();
        //遍歷
        for (Field field : superclassFields) {
        	//創(chuàng)建當(dāng)前日期
            Date now=new Date();
            //如果是插入語(yǔ)句
            if(SqlCommandType.INSERT.equals(sqlCommandType)) {
            	//如果屬性帶有@CreaTime注解,就設(shè)置這個(gè)屬性值為當(dāng)前時(shí)間
                if (field.getAnnotation(CreateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                //如果屬性帶有@UpdateTime注解,就設(shè)置這個(gè)屬性值為當(dāng)前時(shí)間
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
            //如果是插入語(yǔ)句,屬性帶有@UpdateTime注解,就設(shè)置這個(gè)屬性值為當(dāng)前時(shí)間
            if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
        }
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

}

注冊(cè)插件

攔截器以插件的形式,在配置類中向SqlSessionFactoryBean中注冊(cè)插件

package com.example.mybatisinterceptor.config;

import com.example.mybatisinterceptor.interceptor.MybatisInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Mybatis配置類
 * 
 * 該類用于配置Mybatis的相關(guān)設(shè)置,包括數(shù)據(jù)源和攔截器的設(shè)置,以創(chuàng)建SqlSessionFactory。
 */
@Configuration
public class MyConfig {

    /**
     * 創(chuàng)建SqlSessionFactory Bean
     * 
     * @param dataSource 數(shù)據(jù)源,用于連接數(shù)據(jù)庫(kù)
     * @return SqlSessionFactory,Mybatis的會(huì)話工廠,用于創(chuàng)建SqlSession
     * @throws Exception 如果配置過(guò)程中出現(xiàn)錯(cuò)誤,拋出異常
     * 
     * 該方法通過(guò)設(shè)置數(shù)據(jù)源和插件(MybatisInterceptor)來(lái)配置SqlSessionFactoryBean,
     * 最終返回配置好的SqlSessionFactory。
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setPlugins(new MybatisInterceptor());
        return bean.getObject();
    }

}

代碼:https://gitee.com/w452339689/mybatis-interceptor

到此這篇關(guān)于Mybatis攔截器實(shí)現(xiàn)公共字段填充的示例代碼的文章就介紹到這了,更多相關(guān)Mybatis 公共字段填充內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中File與byte[]的互轉(zhuǎn)方式

    Java中File與byte[]的互轉(zhuǎn)方式

    這篇文章主要介紹了Java中File與byte[]的互轉(zhuǎn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • SpringMVC源碼解讀之 HandlerMapping - AbstractDetectingUrlHandlerMapping系列初始化

    SpringMVC源碼解讀之 HandlerMapping - AbstractDetectingUrlHandlerM

    這篇文章主要介紹了SpringMVC源碼解讀之 HandlerMapping - AbstractDetectingUrlHandlerMapping系列初始化的相關(guān)資料,需要的朋友可以參考下
    2016-02-02
  • Java高性能新一代構(gòu)建工具M(jìn)aven-mvnd(實(shí)踐可行版)

    Java高性能新一代構(gòu)建工具M(jìn)aven-mvnd(實(shí)踐可行版)

    這篇文章主要介紹了Java高性能新一代構(gòu)建工具M(jìn)aven-mvnd(實(shí)踐可行版),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-06-06
  • Java后端Tomcat實(shí)現(xiàn)WebSocket實(shí)例教程

    Java后端Tomcat實(shí)現(xiàn)WebSocket實(shí)例教程

    WebSocket protocol 是HTML5一種新的協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工通信(full-duplex)。一開(kāi)始的握手需要借助HTTP請(qǐng)求完成握手。本文給大家介紹Java后端Tomcat實(shí)現(xiàn)WebSocket實(shí)例教程,感興趣的朋友一起學(xué)習(xí)吧
    2016-05-05
  • Java 實(shí)戰(zhàn)項(xiàng)目錘煉之嘟嘟健身房管理系統(tǒng)的實(shí)現(xiàn)流程

    Java 實(shí)戰(zhàn)項(xiàng)目錘煉之嘟嘟健身房管理系統(tǒng)的實(shí)現(xiàn)流程

    讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實(shí)現(xiàn)一個(gè)健身房管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平
    2021-11-11
  • Java使用Swagger接口框架方法詳解

    Java使用Swagger接口框架方法詳解

    這篇文章主要介紹了Java使用Swagger接口框架方法,Swagger是一個(gè)方便我們更好的編寫(xiě)API文檔的框架,而且Swagger可以模擬http請(qǐng)求調(diào)用,感興趣的同學(xué)可以參考下文
    2023-05-05
  • 淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出

    淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出

    這篇文章主要介紹了淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出?具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-09-09
  • java實(shí)現(xiàn)靜默加載Class示例代碼

    java實(shí)現(xiàn)靜默加載Class示例代碼

    這篇文章主要給大家介紹了關(guān)于java實(shí)現(xiàn)靜默加載Class的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • Spring Boot日志技術(shù)logback原理及配置解析

    Spring Boot日志技術(shù)logback原理及配置解析

    這篇文章主要介紹了Spring Boot日志技術(shù)logback原理及用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • java開(kāi)源項(xiàng)目jeecgboot的超詳細(xì)解析

    java開(kāi)源項(xiàng)目jeecgboot的超詳細(xì)解析

    JeecgBoot是一款基于BPM的低代碼平臺(tái),下面這篇文章主要給大家介紹了關(guān)于java開(kāi)源項(xiàng)目jeecgboot的相關(guān)資料,文中通過(guò)圖文以及實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-10-10

最新評(píng)論