自定义注解,mybatis通过拦截器执行insert、update sql自动添加当前时间。

本文介绍如何使用自定义注解和MyBatis拦截器实现数据库操作中时间字段的自动填充,提高开发效率。

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

开发过程中,会经常执行insert、update语句。大部分数据库表结构都有类似create_time这样的时间列,用于记录创建时间。

很多朋友通常会为这个列设置一个默认值、或者通过代码setTime()去设置。这样做是没有问题的。

这里主要提供注解的方式去达到这个目的。有利于提高开发效率。

1、先添加两个自定义注解类:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 时间注解,在实体类对应字段添加注解,插入数据库时会自动添加时间
 * 
 * @author gogym
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface CreateTime {

	String value() default "";
}


//----------------------------这里是两个类,你可以分开创建--------------------------------


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 时间注解,在实体类对应字段添加注解,更新操作时会自动添加时间
 * 
 * @author gogym
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface UpdateTime {

	String value() default "";
}

2、添加mybaits时间注解拦截器,通过拦截器给带注解的实体类属性设置时间:

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;



/**
 * 添加时间注解拦截器,通过拦截sql,自动给带注解的属性添加时间
 * 
 * @author gogym
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class,
    Object.class})})
public class DateTimeInterceptor implements Interceptor
{

    @Override
    public Object intercept(Invocation invocation)
        throws Throwable
    {

        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];

        // 获取 SQL
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

        // 获取参数
        Object parameter = invocation.getArgs()[1];

        // 获取私有成员变量
        Field[] declaredFields = parameter.getClass().getDeclaredFields();

        for (Field field : declaredFields)
        {
            if (field.getAnnotation(CreateTime.class) != null)
            {
                if (SqlCommandType.INSERT.equals(sqlCommandType))
                {
                    // insert语句插入createTime
                    field.setAccessible(true);
                    // 这里设置时间,当然时间格式可以自定。比如转成String类型
                    field.set(parameter, new Date());
                }
            }
            else if (field.getAnnotation(UpdateTime.class) != null)
            {

                if (SqlCommandType.INSERT.equals(sqlCommandType)
                    || SqlCommandType.UPDATE.equals(sqlCommandType))
                {
                    // insert 或update语句插入updateTime
                    field.setAccessible(true);
                    field.set(parameter, new Date());
                }
            }
        }

        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties)
    {}
}

3、配置mybatis拦截器:

你可以通过mybatis的xml文件注册:

<plugins>
		<!--这里配置拦截器-->
        <plugin interceptor="...DateTimeInterceptor"/>

</plugins>

当然如果你用的是spring boot,通过java类注册也可以

import java.util.Properties;

import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.springframework.context.annotation.Bean;

import tk.mybatis.mapper.autoconfigure.ConfigurationCustomizer;

import com.rbl.common.plugin.mybatis.interceptor.DateTimeInterceptor;


@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

	@Bean
	public ConfigurationCustomizer configurationCustomizer() {
		return new ConfigurationCustomizer() {
			@Override
			public void customize(Configuration configuration) {
				// 全局映射器启用缓存
				configuration.setCacheEnabled(false);
				// 查询时,关闭关联对象即时加载以提高性能
				configuration.setLazyLoadingEnabled(false);
				// 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果
				configuration.setMultipleResultSetsEnabled(true);
				// 允许使用列标签代替列名
				configuration.setUseColumnLabel(true);
				// 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL
				configuration
						.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
				// 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE
				configuration.setDefaultExecutorType(ExecutorType.BATCH);
				// 允许在嵌套语句上使用行边界。如果允许,设置false。
				configuration.setSafeRowBoundsEnabled(false);
				// 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能
				configuration.setAggressiveLazyLoading(false);
				// 数据库超过30秒仍未响应则超时
				configuration.setDefaultStatementTimeout(30);
				


				// 注册时间注解拦截器到mybatis
				configuration.addInterceptor(dateTimeInterceptor());
				
			}

		};
	}


    /**
     *这里配置拦截器
    /*
	@Bean
	public DateTimeInterceptor dateTimeInterceptor() {
		return new DateTimeInterceptor();
	}


}

4、使用注解:

使用非常简单,只需要在你需要添加时间的实体类,也就是model里的对应属性添加注解即可,这样当你只需insert或update语句时,就会自动帮你添加上当前系统时间。

    @CreateTime
    private Date createTime;

### 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、付费专栏及课程。

余额充值