mybatis自定义拦截器设置createBy&createTime

本文介绍了如何在MyBatis中自定义拦截器,用于在插入数据时自动填充createBy和createTime字段,提高了代码的复用性和规范性。通过拦截Executor的update方法,解析SQL动态插入相关信息,确保每个新建记录都有准确的创建者和时间戳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Intercepts({
		@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class PrepareInterceptor implements Interceptor {
	@Autowired
	private OAuthUtils oAuthUtils;

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		Object object = invocation.getArgs()[1];
		// sql类型
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

		UserInfo userInfo = oAuthUtils.getUserInfo();
		if (SqlCommandType.INSERT.equals(sqlCommandType)) {
			// 插入操作
			if (object instanceof DefaultSqlSession.StrictMap) {
				// FIXME 批量操作(还有没有别的方式判断?)
				Map map = (DefaultSqlSession.StrictMap) object;
				List list = (List) map.get("list");
				for (Object o : list) {
					reflectCreateInfo(o);
				}
			} else {
				// 单行
				reflec
### MyBatis 拦截器实现自动添加属性 为了实现在MyBatis中通过拦截器自动为实体类的某些字段(如创建时间和更新时间)赋值,可以通过自定义`Interceptor`来完成这一功能。具体来说,在项目中定义一个继承于`org.apache.ibatis.plugin.Interceptor`的类,并利用该类中的方法对目标操作进行增强。 #### 定义 BaseEntity 类 首先,定义一个基础实体类 `BaseEntity` 来统一管理公共的时间戳字段: ```java public class BaseEntity { private Date createTime; private Date updateTime; // getter and setter methods... } ``` 所有需要记录创建时间和更新时间的数据表对应的实体类都应继承这个基类[^1]。 #### 创建自定义拦截器 接着,创建一个新的Java类作为自定义拦截器并标注`@Intercepts`注解指定要拦截的目标对象及其行为。这里选择拦截`Executor.update()`和`Executor.insert()`这两个核心的操作方法以便能够捕获到所有的增删改动作: ```java import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import java.util.Date; import java.util.Properties; @Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}), @Signature(type = Executor.class, method = "insert", args = {MappedStatement.class, Object.class}) }) public class AutoTimestampInterceptor implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { MappedStatement ms = (MappedStatement)invocation.getArgs()[0]; Object parameterObject = invocation.getArgs()[1]; if(parameterObject instanceof BaseEntity){ BaseEntity entity = (BaseEntity)parameterObject; String id = ms.getId(); if(id.endsWith("insert")){ entity.setCreateTime(new Date()); entity.setUpdateTime(entity.getCreateTime()); }else if(id.endsWith("update")){ entity.setUpdateTime(new Date()); } } return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) {} } ``` 上述代码片段展示了如何基于MyBatis提供的API去访问被调用的具体SQL映射语句以及传递给它的参数实例。当检测到传入的对象实现了`BaseEntity`接口时,则为其设定相应的时间戳值[^2]。 #### 配置 Spring Boot 应用程序上下文中注册插件 最后一步是在Spring Boot应用程序配置文件application.yml里声明新的Bean组件以激活此拦截器的作用范围: ```yaml mybatis: configuration: interceptors: - com.example.demo.AutoTimestampInterceptor ``` 或者也可以直接在启动类或者其他任意@Configuration标记过的类里面显式地注入bean: ```java @Bean public AutoTimestampInterceptor autoTimestampInterceptor(){ return new AutoTimestampInterceptor(); } ``` 这样就完成了整个流程的设计与编码工作,每当执行插入或更新数据库记录的动作发生时,都会触发相应的业务逻辑从而达到自动化维护这些特殊列的目的[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值