mybatis自動填充時間字段示例代碼
前言
對于實體中的created_on和updated_on來說,它沒有必要被開發(fā)人員去干預,因為它已經(jīng)足夠說明使用場景了,即在插入數(shù)據(jù)和更新數(shù)據(jù)時,記錄當前時間,這對于mybatis來說,通過攔截器是可以實現(xiàn)的,記得之前說過在jpa中實現(xiàn)的方法,主要通過jpa的注解實現(xiàn)的,因為今天的mybatis需要用到j(luò)ava的攔截器。
下面話不多說了,來一起看看詳細的介紹吧
定義兩個注解
@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; }
定義攔截器,重寫賦值的語句
package com.lind.basic.mybatis; import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler; import java.lang.reflect.Field; import java.time.LocalDateTime; import java.util.Properties; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; /** * 時間攔截器. */ @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 static final Log logger = LogFactory.getLog(com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor.class); private Properties properties; @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; // 獲取 SQL 命令 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); // 獲取參數(shù) Object parameter = invocation.getArgs()[1]; // 獲取私有成員變量 Field[] declaredFields = parameter.getClass().getDeclaredFields(); for (Field field : declaredFields) { if (field.getAnnotation(CreatedOnFuncation.class) != null) { if (SqlCommandType.INSERT.equals(sqlCommandType)) { // insert 語句插入 createTime field.setAccessible(true); field.set(parameter, LocalDateTime.now()); } } if (field.getAnnotation(UpdatedOnFuncation.class) != null) { // insert 或 update 語句插入 updateTime if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) { field.setAccessible(true); field.set(parameter, LocalDateTime.now()); } } } 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()); }
解決是我們所預想的,created_on和updated_on被自動賦上值了。
userinfo:UserInfo ( id=1085780948955959297, name=lind, email=test@sina.com, createdOn=2019-01-17T14:08:45.665, updatedOn=2019-01-17T14:08:45.665 )
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Java實戰(zhàn)之酒店人事管理系統(tǒng)的實現(xiàn)
這篇文章主要介紹了如何用Java實現(xiàn)酒店人事管理系統(tǒng),文中采用的技術(shù)有:JSP、Spring、SpringMVC、MyBatis等,感興趣的小伙伴可以學習一下2022-03-03Java中BigInteger類的使用方法詳解(全網(wǎng)最新)
這篇文章主要介紹了Java中BigInteger類的使用方法詳解,常用最全系列,本章作為筆記使用,內(nèi)容比較全面,但常用的只有:構(gòu)造函數(shù),基本運算以及compareTo(),intValue(),setBit(),testBit()方法,需要的朋友可以參考下2023-05-05Java項目開啟遠程調(diào)試的方法步驟(tomcat、springboot)
這篇文章主要介紹了Java項目開啟遠程調(diào)試的方法步驟(tomcat、springboot),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10Java中StringBuilder與StringBuffer使用及源碼解讀
我們前面學習的String就屬于不可變字符串,因為理論上一個String字符串一旦定義好,其內(nèi)容就不可再被改變,但實際上,還有另一種可變字符串,包括StringBuilder和StringBuffer兩個類,那可變字符串有什么特點,又怎么使用呢,接下來就請大家跟我一起來學習吧2023-05-05