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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java編程實現(xiàn)基于用戶的協(xié)同過濾推薦算法代碼示例
這篇文章主要介紹了Java編程實現(xiàn)基于用戶的協(xié)同過濾推薦算法代碼示例,具有一定參考價值,需要的朋友可以了解下。2017-11-11
Spring Boot控制層參數(shù)綁定@RequestPart 注解的使用
@RequestPart是一個非常重要但常被忽略的注解,專門用于處理multipart/form-data請求中的復雜數(shù)據(jù)類型,下面給大家介紹Spring Boot控制層參數(shù)綁定@RequestPart 注解的使用,感興趣的朋友跟隨小編一起看看吧2026-02-02
Java thread.isInterrupted() 返回值不確定結果分析解決
這篇文章主要介紹了Java thread.isInterrupted() 返回值不確定結果分析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-12-12
Java實戰(zhàn)之實現(xiàn)文件資料上傳并生成縮略圖
這篇文章主要介紹了通過Java實現(xiàn)文件資料的上傳并生成一個縮略圖,文中的示例代碼講解詳細,對我們學習Java有一定的幫助,感興趣的小伙伴可以了解一下2021-12-12
Spring中@RestControllerAdvice注解的使用詳解
這篇文章主要介紹了Spring中@RestControllerAdvice注解的使用詳解,@RestControllerAdvice是一個組合注解,由@ControllerAdvice、@ResponseBody組成,而@ControllerAdvice繼承了@Component,需要的朋友可以參考下2024-01-01
Java中double數(shù)值保留兩位小數(shù)的4種實現(xiàn)方式舉例
在Java編程中,我們經(jīng)常遇到需要對double類型的浮點數(shù)進行精確截斷或四舍五入保留兩位小數(shù)的需求,這篇文章主要給大家介紹了關于Java中double數(shù)值保留兩位小數(shù)的4種實現(xiàn)方式,需要的朋友可以參考下2024-07-07
Java編程實現(xiàn)數(shù)組轉(zhuǎn)成list及l(fā)ist轉(zhuǎn)數(shù)組的方法
這篇文章主要介紹了Java編程實現(xiàn)數(shù)組轉(zhuǎn)成list及l(fā)ist轉(zhuǎn)數(shù)組的方法,結合實例形式較為詳細的總結分析了java實現(xiàn)數(shù)組與list之間相互轉(zhuǎn)換的操作技巧,需要的朋友可以參考下2017-09-09

