自定义mybatis拦截器,在若依springboot项目中不起作用的原因

自定义mybatis拦截器,在若依springboot项目中不起作用的原因

找到 MyBatisConfig 配置类,引入自定义配置
在这里插入图片描述
在sqlSessionFactory中添加自定义拦截器,就可以正常使用了
在这里插入图片描述

package com.lingxu.framework.config;

import com.lingxu.common.core.domain.model.LoginUser;
import com.lingxu.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
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.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * mybatis拦截器,自动注入创建人、创建时间、修改人、修改时间
 * @Author scott
 * @Date  2019-01-19
 *
 */
@Slf4j
@Component
@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) invocation.getArgs()[0];
		String sqlId = mappedStatement.getId();
		log.debug("------sqlId------" + sqlId);
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		Object parameter = invocation.getArgs()[1];
		log.debug("------sqlCommandType------" + sqlCommandType);

		if (parameter == null) {
			return invocation.proceed();
		}
		if (SqlCommandType.INSERT == sqlCommandType) {
			LoginUser sysUser = this.getLoginUser();
			Field[] fields = this.getAllFields(parameter);
			assert fields != null;
			for (Field field : fields) {
				log.debug("------field.name------" + field.getName());
				try {
					if ("createBy".equals(field.getName())) {
						field.setAccessible(true);
						Object local_createBy = field.get(parameter);
						field.setAccessible(false);
						if (local_createBy == null || local_createBy.equals("")) {
							if (sysUser != null) {
								// 登录人账号
								field.setAccessible(true);
								field.set(parameter, sysUser.getUserId());
								field.setAccessible(false);
							}
						}
					}
					if ("createName".equals(field.getName())) {
						field.setAccessible(true);
						Object local_createBy = field.get(parameter);
						field.setAccessible(false);
						if (local_createBy == null || local_createBy.equals("")) {
							if (sysUser != null) {
								// 登录人账号
								field.setAccessible(true);
								field.set(parameter, sysUser.getUser().getNickName());
								field.setAccessible(false);
							}
						}
					}
					// 注入创建时间
					if ("createTime".equals(field.getName())) {
						field.setAccessible(true);
						Object local_createDate = field.get(parameter);
						field.setAccessible(false);
						if (local_createDate == null || local_createDate.equals("")) {
							field.setAccessible(true);
							field.set(parameter, new Date());
							field.setAccessible(false);
						}
					}

				} catch (Exception e) {
				}
			}
		}
		if (SqlCommandType.UPDATE == sqlCommandType) {
			LoginUser sysUser = this.getLoginUser();
			Field[] fields = null;
			if (parameter instanceof ParamMap) {
				ParamMap<?> p = (ParamMap<?>) parameter;
				//update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
				if (p.containsKey("et")) {
					parameter = p.get("et");
				} else {
					parameter = p.get("param1");
				}
				//update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-

				//update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
				if (parameter == null) {
					return invocation.proceed();
				}
				//update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-

				fields = this.getAllFields(parameter);
			} else {
				fields = this.getAllFields(parameter);
			}

			for (Field field : fields) {
				field.setAccessible(true);
				log.debug("------field.name------" + field.getName());
				try {
					if ("updateBy".equals(field.getName())) {
						//获取登录用户信息
						if (sysUser != null) {
							// 登录账号
							field.set(parameter, sysUser.getUserId());
							field.setAccessible(false);
						}
					}
					if ("updateTime".equals(field.getName())) {
						field.set(parameter, new Date());
						field.setAccessible(false);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	private LoginUser getLoginUser() {
		LoginUser userNow = null;
		try {
//			try catch避免线程任务出错
			userNow = SecurityUtils.getLoginUser() != null ? SecurityUtils.getLoginUser() : null;
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return userNow;
	}

	/**
	 * 获取类的所有属性,包括父类
	 *
	 * @param object
	 * @return
	 */
	public Field[] getAllFields(Object object) {
		Class<?> clazz = object.getClass();
		if(clazz==null){
			return  null;
		}
		List<Field> fieldList = new ArrayList<>();
		while (clazz != null) {
			fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
			clazz = clazz.getSuperclass();
		}
		Field[] fields = new Field[fieldList.size()];
		fieldList.toArray(fields);
		return fields;
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring BootMyBatis 结合使用时,自定义拦截器是一种强大的工具,允许开发者在执行 SQL 之前、之后或在特定业务逻辑点进行额外的操作。以下是如何使用自定义拦截器的一般步骤: 1. **创建拦截器接口**: 首先,你需要定义一个实现了 `org.apache.ibatis.interceptor.Interceptor` 接口的类,这个类通常是抽象的,包含你想要执行的业务逻辑方法。 ```java public interface CustomInterceptor extends Interceptor { // 自定义方法,例如预处理SQL前、后操作 Object before(Invocation invocation); // 其他可能的方法,如执行SQL后处理 Object after(Invocation invocation) throws Throwable; } ``` 2. **实现具体拦截器类**: 在具体类,你需要重写上述接口的方法,并添加你需要的业务逻辑。 ```java public class YourCustomInterceptor implements CustomInterceptor { @Override public Object before(Invocation invocation) { // 在这里执行预处理操作 Object parameter = invocation.getArgs(); // 获取参数 // ...你的代码... return parameter; // 返回处理后的参数 } @Override public Object after(Invocation invocation) { // 执行SQL后处理 // ...你的代码... } } ``` 3. **注册拦截器**: 在 Spring BootMyBatis 配置,通过 `SqlSessionFactoryBean` 或者 `SqlSessionBuilder` 注册你的拦截器。可以通过 `interceptors` 属性来添加自定义拦截器列表。 ```java @Configuration public class MyBatisConfig { @Bean public SqlSessionFactory sqlSessionFactory(MyBatisMapperScannerConfigurer scannerConfigurer) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setMapperScannerConfigurer(scannerConfigurer); // 添加你的拦截器 factoryBean.setPlugins(Arrays.asList(new YourCustomInterceptor())); return factoryBean.getObject(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值