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

开发过程中,会经常执行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可以通过Java的反射机制和myBatis拦截器来实现在插入和更新操作时自动设置“创建时间”和“最后修改时间”的功能。 1. 自动插入“创建时间” 在插入数据时,我们可以在Java对象中设置“创建时间”字段的值为当前时间,然后将该Java对象传递给myBatisSQL语句执行。例如: ```java public class User { private Long id; private String name; private Date createTime; // getter/setter 略 // 在插入数据时自动设置创建时间 public void preInsert() { this.createTime = new Date(); } } ``` 在上面的代码中,我们定义了一个`preInsert`方法,在该方法中将“创建时间”字段的值设置为当前时间。在执行插入操作前,我们可以通过myBatis的`Interceptor`拦截器来调用该方法。 2. 自动更新“最后修改时间” 在更新数据时,我们可以在Java对象中设置“最后修改时间”字段的值为当前时间,然后将该Java对象传递给myBatisSQL语句执行。例如: ```java public class User { private Long id; private String name; private Date createTime; private Date updateTime; // getter/setter 略 // 在更新数据时自动设置最后修改时间 public void preUpdate() { this.updateTime = new Date(); } } ``` 在上面的代码中,我们定义了一个`preUpdate`方法,在该方法中将“最后修改时间”字段的值设置为当前时间。在执行更新操作前,我们可以通过myBatis的`Interceptor`拦截器来调用该方法。 3. 使用myBatis的Interceptor实现自动插入“创建时间”和更新“最后修改时间myBatis的`Interceptor`拦截器可以拦截SQL语句的执行,我们可以在拦截器中判断SQL语句的类型,然后调用Java对象的`preInsert`或`preUpdate`方法设置对应的时间字段的值。例如: ```java @Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) }) public class TimeInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; SqlCommandType sqlCommandType = ms.getSqlCommandType(); if (parameter != null) { if (sqlCommandType == SqlCommandType.INSERT) { Method method = parameter.getClass().getMethod("preInsert"); if (method != null) { method.invoke(parameter); } } else if (sqlCommandType == SqlCommandType.UPDATE) { Method method = parameter.getClass().getMethod("preUpdate"); if (method != null) { method.invoke(parameter); } } } return invocation.proceed(); } } ``` 在上面的代码中,我们定义了一个`TimeInterceptor`拦截器,通过myBatis的`@Intercepts`和`@Signature`注解指定拦截的方法为`Executor.update`,拦截的参数类型为`MappedStatement.class, Object.class`。 在`intercept`方法中,我们首先获取SQL语句的类型,然后判断参数是否为Java对象,如果是则调用相应的`preInsert`或`preUpdate`方法设置时间字段的值。最后返回拦截器链的执行结果。 最后,我们需要在myBatis的配置文件中配置拦截器: ```xml <configuration> <plugins> <plugin interceptor="com.example.TimeInterceptor"/> </plugins> </configuration> ``` 以上就是使用myBatis实现自动插入“创建时间”和更新“最后修改时间”的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值