说明
基于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拦截器
根据实体来选一种就行
实体没有父类的情况
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拦截器实现类,用于在插入或更新操作中自动处理创建时间、更新时间和自增ID。
*/
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {
/**
* 对执行的SQL命令进行拦截处理。
*
* @param invocation 拦截器调用对象,包含方法参数和目标对象等信息。
* @return 继续执行目标方法后的返回结果。
* @throws Throwable 方法执行可能抛出的异常。
*/
@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();
}
/**
* 设置参数的创建时间和更新时间,以及自增ID。
*
* @param parameter 待处理的参数对象。
* @param sqlCommandType SQL命令类型,用于区分插入还是更新操作。
* @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);
}
}
}
}
}
/**
* 给目标对象创建一个代理。
*
* @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包括方法名和要操作的参数值
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
//sql语句的类型
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();
}
/**
* 设置值
* @param parameter sql中对象的值
* @param sqlCommandType sql执行类型
* @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,替换参数的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,替换参数的id
field.set(parameter, IdUtil.simpleUUID());
}
}
}
}
}
//如果是继承了基类,创建时间和修改时间都在基类中,先获取基类class
Class<?> superclass = aClass.getSuperclass();
//获取所有属性
Field[] superclassFields = superclass.getDeclaredFields();
//遍历
for (Field field : superclassFields) {
//创建当前日期
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的相关设置,包括数据源和拦截器的设置,以创建SqlSessionFactory。
*/
@Configuration
public class MyConfig {
/**
* 创建SqlSessionFactory Bean
*
* @param dataSource 数据源,用于连接数据库
* @return SqlSessionFactory,Mybatis的会话工厂,用于创建SqlSession
* @throws Exception 如果配置过程中出现错误,抛出异常
*
* 该方法通过设置数据源和插件(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();
}
}