jpa 自定义sql if_mybatis仿jpa 使用@createDate @updateDate
最近在使用mybatis的時(shí)候發(fā)現(xiàn)一個(gè)問題,就是好多的時(shí)候保存實(shí)體的時(shí)候,都要set create 和update,這樣很麻煩,有沒有可能類似jap 使用注解自動(dòng)生成。jpa 的注解原理也攔截sql ,把sql 里面的參數(shù)綁定給修改一下。?
了解了原理,我們也就自己可以可以自己仿照jpa 實(shí)現(xiàn)一下了。
先自定義兩個(gè)注解@createDate,@updateDate
項(xiàng)目原理,使用mybatis?的攔截器,攔截Executor,的update?方法,
里面?兩個(gè)參數(shù)
根據(jù)MappedStatement 獲取sql 的注解枚舉類型, Object 是入?yún)?#xff0c;?在根據(jù)入?yún)?object 獲取屬性列表,看屬性上面是否存在?自定義的注解,不同的注解使用場(chǎng)合不同,在用反射給filed set值。?
看一下代碼
自定義攔截器
@Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),})public class DatePlugin implements Interceptor { @Override public Object intercept(Invocation invocation) throws Exception { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; // 獲取 SQL 命令 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); // 獲取參數(shù) Object parameter = invocation.getArgs()[1]; List parameterMappings = mappedStatement.getParameterMap().getParameterMappings(); // 獲取私有成員變量 Field[] declaredFields = parameter.getClass().getDeclaredFields(); // 插入要修改兩個(gè)值 for (Field field : declaredFields) { if (SqlCommandType.INSERT.equals(sqlCommandType)) { if (!ObjectUtils.isEmpty(field.getAnnotation(CreateDate.class))) { field.setAccessible(true); field.set(parameter, new Timestamp(System.currentTimeMillis())); } if (!ObjectUtils.isEmpty(field.getAnnotation(UpdateDate.class))) { field.setAccessible(true); field.set(parameter, new Timestamp(System.currentTimeMillis())); } } // update 只要修改一個(gè)值 if (SqlCommandType.UPDATE.equals(sqlCommandType)) { if (!ObjectUtils.isEmpty(field.getAnnotation(UpdateDate.class))) { field.setAccessible(true); field.set(parameter, new Timestamp(System.currentTimeMillis())); } } } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { }}實(shí)體:
現(xiàn)在把?
這個(gè)插件加入mybatis 的配置中。
一般情況下我們是這樣配置的
但是這樣是有問題的,我們啟動(dòng)看一下
類型轉(zhuǎn)換錯(cuò)誤,這是因?yàn)樗氖穷恗ybatis.configuration.interceptors 不是字符串,?
我們看一下mybatis 官網(wǎng)
我們只要聲明他是一個(gè)bean會(huì)自動(dòng)注入的。
我們來寫一個(gè)測(cè)試類
啟動(dòng)項(xiàng)目運(yùn)行一下,別忘記了
打印sql?
啟動(dòng)調(diào)用一下接口?
creatdate 和updatedate 沒有值,?在把實(shí)體的注解加上
再跑一下
成功了,喜歡,點(diǎn)贊,轉(zhuǎn)發(fā)。
總結(jié)
以上是生活随笔為你收集整理的jpa 自定义sql if_mybatis仿jpa 使用@createDate @updateDate的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果用户福利!免费领取《英雄联盟》交通卡
- 下一篇: 直线电机原理动画_最新的3D动画演示:同