做网页专题 应该关注哪些网站,网页版梦幻西游吸血鬼怎么过,ps素材库,o2o网站咋建设最近在使用mybatis的时候发现一个问题,就是好多的时候保存实体的时候#xff0c;都要set create 和update,这样很麻烦#xff0c;有没有可能类似jap 使用注解自动生成。jpa 的注解原理也拦截sql ,把sql 里面的参数绑定给修改一下。 了解了原理#xff0c;我们也就自己可以可… 最近在使用mybatis的时候发现一个问题,就是好多的时候保存实体的时候都要set create 和update,这样很麻烦有没有可能类似jap 使用注解自动生成。jpa 的注解原理也拦截sql ,把sql 里面的参数绑定给修改一下。 了解了原理我们也就自己可以可以自己仿照jpa 实现一下了。先自定义两个注解createDate,updateDate项目原理使用mybatis 的拦截器拦截Executor的update 方法里面 两个参数根据MappedStatement 获取sql 的注解枚举类型 Object 是入参 在根据入参 object 获取属性列表看属性上面是否存在 自定义的注解不同的注解使用场合不同在用反射给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(); // 获取参数 Object parameter invocation.getArgs()[1]; List parameterMappings mappedStatement.getParameterMap().getParameterMappings(); // 获取私有成员变量 Field[] declaredFields parameter.getClass().getDeclaredFields(); // 插入要修改两个值 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 只要修改一个值 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) { }}实体现在把 这个插件加入mybatis 的配置中。一般情况下我们是这样配置的但是这样是有问题的我们启动看一下类型转换错误这是因为他要的是类mybatis.configuration.interceptors 不是字符串 我们看一下mybatis 官网我们只要声明他是一个bean会自动注入的。我们来写一个测试类启动项目运行一下别忘记了打印sql 启动调用一下接口 creatdate 和updatedate 没有值 在把实体的注解加上再跑一下成功了喜欢点赞转发。