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í)行目標方法后的返回結(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ù)的創(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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringMVC源碼解讀之 HandlerMapping - AbstractDetectingUrlHandlerM
這篇文章主要介紹了SpringMVC源碼解讀之 HandlerMapping - AbstractDetectingUrlHandlerMapping系列初始化的相關資料,需要的朋友可以參考下2016-02-02
Java高性能新一代構(gòu)建工具Maven-mvnd(實踐可行版)
這篇文章主要介紹了Java高性能新一代構(gòu)建工具Maven-mvnd(實踐可行版),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06
Java后端Tomcat實現(xiàn)WebSocket實例教程
WebSocket protocol 是HTML5一種新的協(xié)議。它實現(xiàn)了瀏覽器與服務器全雙工通信(full-duplex)。一開始的握手需要借助HTTP請求完成握手。本文給大家介紹Java后端Tomcat實現(xiàn)WebSocket實例教程,感興趣的朋友一起學習吧2016-05-05
Java 實戰(zhàn)項目錘煉之嘟嘟健身房管理系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實現(xiàn)一個健身房管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11
淺談springboot項目中定時任務如何優(yōu)雅退出
這篇文章主要介紹了淺談springboot項目中定時任務如何優(yōu)雅退出?具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

