mybatis自(zi)動填充時間字段
對于實體中的created_on和updated_on來說(shuo),它(ta)沒有必要被(bei)開(kai)發人員去干預(yu),因為它(ta)已經(jing)足夠說(shuo)明使用場景了,即在(zai)插入(ru)數據(ju)和(he)更新(xin)數據(ju)時,記錄當前時間,這(zhe)對于(yu)mybatis來說(shuo),通過(guo)(guo)攔截(jie)器是可以實(shi)(shi)現的,記得之前說(shuo)過(guo)(guo)在(zai)jpa中實(shi)(shi)現的方法,主要通過(guo)(guo)jpa的注解實(shi)(shi)現的,因為今天(tian)的mybatis需要用到java的攔截(jie)器。
定義兩個注解
@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.FIELD})
public @interface CreatedOnFuncation {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.FIELD})
public @interface UpdatedOnFuncation {
String value() default "";
}
使用這兩個注解
@Getter
@Builder(toBuilder = true)
@ToString
public class UserInfo {
private Long id;
private String name;
private String email;
@CreatedOnFuncation
private LocalDateTime createdOn;
@UpdatedOnFuncation
private LocalDateTime updatedOn;
}
定義攔截器,重寫賦值的語句
/**
* 時間攔截器.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
@Intercepts({@Signature(
type = org.apache.ibatis.executor.Executor.class,
method = "update",
args = {MappedStatement.class, Object.class})})
public class CreateUpdateTimeInterceptor extends AbstractSqlParserHandler implements Interceptor {
private Properties properties;
@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();
if (parameter.getClass().getSuperclass() != null) {
Field[] superField = parameter.getClass().getSuperclass().getDeclaredFields();
declaredFields = ArrayUtils.addAll(declaredFields, superField);
}
// 是否為mybatis plug
boolean isPlugUpdate = parameter.getClass().getDeclaredFields().length == 1
&& parameter.getClass().getDeclaredFields()[0].getName().equals("serialVersionUID");
//兼容mybatis plus的update
if (isPlugUpdate) {
Map<String, Object> updateParam = (Map<String, Object>) parameter;
Class<?> updateParamType = updateParam.get("param1").getClass();
declaredFields = updateParamType.getDeclaredFields();
if (updateParamType.getSuperclass() != null) {
Field[] superField = updateParamType.getSuperclass().getDeclaredFields();
declaredFields = ArrayUtils.addAll(declaredFields, superField);
}
}
for (Field field : declaredFields) {
// insert
if (field.getAnnotation(CreatedOnFuncation.class) != null) {
if (SqlCommandType.INSERT.equals(sqlCommandType)) {
field.setAccessible(true);
field.set(parameter, new Timestamp(System.currentTimeMillis()));
}
}
// update
if (field.getAnnotation(UpdatedOnFuncation.class) != null) {
if (SqlCommandType.INSERT.equals(sqlCommandType)
|| SqlCommandType.UPDATE.equals(sqlCommandType)) {
field.setAccessible(true);
//兼容mybatis plus的update
if (isPlugUpdate) {
Map<String, Object> updateParam = (Map<String, Object>) parameter;
field.set(updateParam.get("param1"), new Timestamp(System.currentTimeMillis()));
} else {
field.set(parameter, new Timestamp(System.currentTimeMillis()));
}
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof org.apache.ibatis.executor.Executor) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties prop) {
this.properties = prop;
}
}
添加測試用例
@Test
public void insert() {
UserInfo userInfo = UserInfo.builder()
.name("lind")
.email("test@sina.com")
.build();
userInfoMapper.insert(userInfo);
System.out.println("userinfo:" + userInfo.toString());
}
解決是我們(men)所預想的,created_on和updated_on被(bei)自(zi)動賦(fu)上值(zhi)了。
userinfo:UserInfo
(
id=1085780948955959297,
name=lind,
email=test@sina.com,
createdOn=2019-01-17T14:08:45.665,
updatedOn=2019-01-17T14:08:45.665
)