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

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

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

說明

基于springBoot+mybatis,三步完成

  • 編寫注解,然后將注解放在對應的想要填充的字段上
  • 編寫攔截器
  • 注冊攔截器

注解

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ù)實體來選一種就行

實體沒有父類的情況

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

    /**
     * 對執(zhí)行的SQL命令進行攔截處理。
     * 
     * @param invocation 攔截器調(diào)用對象,包含方法參數(shù)和目標對象等信息。
     * @return 繼續(xù)執(zhí)行目標方法后的返回結果。
     * @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ù)的創(chuàng)建時間和更新時間,以及自增ID。
     * 
     * @param parameter 待處理的參數(shù)對象。
     * @param sqlCommandType SQL命令類型,用于區(qū)分插入還是更新操作。
     * @throws Throwable 設置字段值可能拋出的異常。
     */
    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);
                    }
                }
            }
        }
    }

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

實體有父類的情況

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語句的類型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //判斷是不是插入或者修改
        if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
        	//獲取參數(shù)
            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();
    }

    /**
     * 設置值
     * @param parameter     sql中對象的值
     * @param sqlCommandType        sql執(zhí)行類型
     * @throws Throwable
     */
    public void setParameter(Object parameter, SqlCommandType sqlCommandType) throws Throwable {
    	//獲取對象class
        Class<?> aClass = parameter.getClass();
        //獲取所有屬性
        Field[] declaredFields;
        declaredFields = aClass.getDeclaredFields();
        //遍歷屬性
        for (Field field : declaredFields) {
        	//如果是插入語句
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
            	//獲取屬性的注解,如果注解是@AutoId,代表它是id
                if (field.getAnnotation(AutoId.class) != null ) {
                	//繞過檢查
                    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)) {	//否則生成簡單id,替換參數(shù)的id
                            field.set(parameter, IdUtil.simpleUUID());
                        }
                    }
                }
            }
        }
		//如果是繼承了基類,創(chuàng)建時間和修改時間都在基類中,先獲取基類class
        Class<?> superclass = aClass.getSuperclass();
        //獲取所有屬性
        Field[] superclassFields = superclass.getDeclaredFields();
        //遍歷
        for (Field field : superclassFields) {
        	//創(chuàng)建當前日期
            Date now=new Date();
            //如果是插入語句
            if(SqlCommandType.INSERT.equals(sqlCommandType)) {
            	//如果屬性帶有@CreaTime注解,就設置這個屬性值為當前時間
                if (field.getAnnotation(CreateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                //如果屬性帶有@UpdateTime注解,就設置這個屬性值為當前時間
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
            //如果是插入語句,屬性帶有@UpdateTime注解,就設置這個屬性值為當前時間
            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);
    }

}

注冊插件

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

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的相關設置,包括數(shù)據(jù)源和攔截器的設置,以創(chuàng)建SqlSessionFactory。
 */
@Configuration
public class MyConfig {

    /**
     * 創(chuàng)建SqlSessionFactory Bean
     * 
     * @param dataSource 數(shù)據(jù)源,用于連接數(shù)據(jù)庫
     * @return SqlSessionFactory,Mybatis的會話工廠,用于創(chuàng)建SqlSession
     * @throws Exception 如果配置過程中出現(xiàn)錯誤,拋出異常
     * 
     * 該方法通過設置數(shù)據(jù)源和插件(MybatisInterceptor)來配置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

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

相關文章

最新評論

馆陶县| 镇安县| 翁源县| 郁南县| 岳阳县| 杭州市| 青冈县| 长沙县| 新余市| 西充县| 石景山区| 连云港市| 三都| 三都| 东辽县| 邻水| 绍兴县| 延长县| 中牟县| 宣武区| 新巴尔虎右旗| 湄潭县| 马山县| 大冶市| 邳州市| 新野县| 汨罗市| 长宁县| 洞头县| 永川市| 沅江市| 定远县| 岢岚县| 隆林| 集安市| 长沙市| 乐清市| 醴陵市| 榆中县| 金秀| 沽源县|