• tk.mybatis通用插件updateByPrimaryKeySelective无法自动更新ON UPDATE CURRENT_TIMESTAMP列的解决办法


    tk.mybatis是一个很好用的通用插件,把CRUD这些基本的数据操作全都用动态SQL语句自动生成了,mapper和xml里十分清爽,但是昨天发现有一个小坑,记录在此:

    有一张表,结构如下(已经简化了):

    CREATE TABLE `t_sample` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
      `empcode` varchar(8) NOT NULL DEFAULT '' COMMENT '员工号',
      `datachange_lasttime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '时间戳',
      PRIMARY KEY (`id`),
      UNIQUE KEY `idx_unique_empcode` (`empcode`),
      KEY `idx_datachange_lasttime` (`datachange_lasttime`)
    ) ENGINE=InnoDB AUTO_INCREMENT=561 DEFAULT CHARSET=utf8mb4 COMMENT='test'
    

    有一列datachange_lasttime,设置了update时, 让mysql自动更新成当前时间,这样只要记录有变化,通过这一列就能知道什么时候变化的(这也是很多公司的数据库开发规范之一)

    然后tk.mybatis里提供了一个很方便的方法:updateByPrimaryKeySelective,用法如下:

        @Test
        public void testDataChangeLastTime() {
            SampleEntity sample = sampleEntityMapper.selectByPrimaryKey(560);
            long changeLastTime1 = sample.getDatachangeLasttime().getTime();
            sample.setEmpcode("TEST");
            int affectedRows = sampleEntityMapper.updateByPrimaryKeySelective(sample);
            System.out.println(affectedRows);
            long changeLastTime2 = sample.getDatachangeLasttime().getTime();
    
            Assert.assertNotEquals(changeLastTime1, changeLastTime2);
        }
    

    代码很简单,先根据主键id,取出一条记录,然后再根据业务要求,修改某一列,然后提交。运行后,发现datachange_lasttime这列并没按预期那样,更新成当前时间,仍然是旧的时间戳。(上面的单元测试将会失败)

    把日志级别调整成DEBUG,观察了下最终生成的update语句,如下:

    22:41:23.933 [main] DEBUG  - ==> Preparing: UPDATE t_sample SET id = id,empcode = ?,datachange_lasttime = ? WHERE id = ?
    22:41:23.936 [main] DEBUG  - ==> Parameters: TEST(String), 2018-09-07 17:01:39.0(Timestamp), 560(Long)
    22:41:23.981 [main] DEBUG  - <== Updates: 1

    可能大家一眼就看出问题了,update语句里, datachange_lasttime这列,又用旧值重新更新回去了。

    updateByPrimaryKeySelective的原理,是根据entity对象的属性值,是否为null,如果为null,则最终生成的update语句里,将忽略该列,否则会更新该列。

    entity从数据库里取出来时,DatachangeLasttime属性上已经有值了,不为null,所以更新时,又把这个旧值给update回去了!解决办法:

        @Test
        public void testDataChangeLastTime() {
            SampleEntity sample = sampleEntityMapper.selectByPrimaryKey(560);
            long changeLastTime1 = sample.getDatachangeLasttime().getTime();
            //注意:就本例而言,如果empCode在数据库里的旧值本身是TEST,这一行不会被更新(datachange_lasttime列仍是旧值)
            sample.setEmpcode("TEST");
            //人为更新成null,以便让mybatis生成的update的语句忽略
            sample.setDatachangeLasttime(null);
            int affectedRows = sampleEntityMapper.updateByPrimaryKeySelective(sample);
            System.out.println(affectedRows);
            long changeLastTime2 = sample.getDatachangeLasttime().getTime();
    
            Assert.assertNotEquals(changeLastTime1, changeLastTime2);
        }
    

    手动把DatachangeLasttime属性设置为null即可,这次生成的udpate语句为:

    22:44:06.298 [main] DEBUG  - ==> Preparing: UPDATE t_sample SET id = id,empcode = ? WHERE id = ?
    22:44:06.300 [main] DEBUG  - ==> Parameters: TEST(String), 560(Long)
    22:44:06.342 [main] DEBUG  - <== Updates: 1

    另外还有一个小细节,跟mybatis无关,是mysql自己的机制,如果empcode这列在数据库里,这行上的旧值已经是TEST,java代码又把更新成TEST,即:这行的数据没有变化,updateByPrimaryKeySelective在java代码里返回的影响行数,仍然是1 ,但是在mysql里裸跑sql的话,影响行数是0,即:数据库层面这行没有更新,datachange_lasttime列当然仍是旧值(这倒也合理,毕竟数据更新前后的数据一样,所以mysql不更新也说得过去)

    最后,来点优雅的做法,毕竟大家都是有身份~~~~~"证"的人,怎么可能手动在每个需要更新的地方,手动设置null,这有点low,讲出去要被人笑话的^_~

    mybatis提供了拦截器机制,搞一个拦截器在更新前拦截一下,用反射大法把这列设置成null,就万事大吉了。

    /**
     *
     * @author 菩提树下的杨过(http://yjmyzz.cnblogs.com)
     * @date 2018/12/15 5:17 PM
     */
    @Intercepts({
            @Signature(type = Executor.class, method = DataChangeLastTimeInterceptor.METHOD_UPDATE, args = {
                    MappedStatement.class, Object.class})})
    public class DataChangeLastTimeInterceptor implements Interceptor {
    
        Logger logger = LoggerFactory.getLogger(this.getClass());
    
        public static final String METHOD_UPDATE = "update";
        public static final String[] METHOD_SET_DATA_CHANGE_LAST_TIME = new String[]{"setDatachangeLasttime", "setDataChange_LastTime"};
    
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            String methodName = invocation.getMethod().getName();
            if (methodName.equalsIgnoreCase(DataChangeLastTimeInterceptor.METHOD_UPDATE)) {
                Object parameter = invocation.getArgs()[1];
                Date empty = null;
                try {
                    for (String s : METHOD_SET_DATA_CHANGE_LAST_TIME) {
                        ReflectionUtils.callMethod(parameter, s, true, empty);
                    }
                } catch (Exception e) {
                    logger.warn("setDatachangeLasttime error:" + e.getMessage() + ",class:" + parameter.getClass());
                }
            }
            return invocation.proceed();
        }
    
        @Override
        public Object plugin(Object o) {
            return Plugin.wrap(o, this);
        }
    
        @Override
        public void setProperties(Properties properties) {
    
        }
    }
    

    这里面有一个自己写的反射工具类,代码如下:

    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Member;
    import java.lang.reflect.Method;
    import org.apache.commons.lang3.ArrayUtils;
    
    public class ReflectionUtils {
    
        static Boolean checkName(Member member, String targetName, Boolean ignoreCase) {
            if (ignoreCase) {
                if (member.getName().equalsIgnoreCase(targetName)) {
                    return true;
                }
            } else if (member.getName().equals(targetName)) {
                return true;
            }
    
            return false;
        }
    
        public static Method getMethod(Object target, String methodName, Boolean ignoreCase) {
            if (target == null) {
                return null;
            } else {
                Method[] methods = target.getClass().getDeclaredMethods();
                if (ArrayUtils.isEmpty(methods)) {
                    return null;
                } else {
                    Method[] arr$ = methods;
                    int len$ = methods.length;
    
                    for(int i$ = 0; i$ < len$; ++i$) {
                        Method method = arr$[i$];
                        if (checkName(method, methodName, ignoreCase)) {
                            return method;
                        }
                    }
    
                    return null;
                }
            }
        }
    
        public static Method getMethod(Object target, String methodName) {
            return getMethod(target, methodName, false);
        }
    
        public static Field getField(Object target, String propertyName, Boolean ignoreCase) {
            if (target == null) {
                return null;
            } else {
                Field[] fields = target.getClass().getDeclaredFields();
                if (ArrayUtils.isEmpty(fields)) {
                    return null;
                } else {
                    Field[] arr$ = fields;
                    int len$ = fields.length;
    
                    for(int i$ = 0; i$ < len$; ++i$) {
                        Field f = arr$[i$];
                        if (checkName(f, propertyName, ignoreCase)) {
                            return f;
                        }
                    }
    
                    return null;
                }
            }
        }
    
        public static Field getField(Object target, String propertyName) {
            return getField(target, propertyName, false);
        }
    
        public static void setField(Object target, String propertyName, Boolean ignoreCase, Object propertyValue) throws IllegalAccessException {
            Field field = getField(target, propertyName, ignoreCase);
            if (field != null) {
                field.set(target, propertyValue);
            }
    
        }
    
        public static void setField(Object target, String propertyName, Object propertyValue) throws IllegalAccessException {
            setField(target, propertyName, false, propertyValue);
        }
    
        public static void callMethod(Object target, String methodName, Object... args) throws InvocationTargetException, IllegalAccessException {
            callMethod(target, methodName, false, args);
        }
    
        public static void callMethod(Object target, String methodName, Boolean ignoreCase, Object... args) throws InvocationTargetException, IllegalAccessException {
            Method method = getMethod(target, methodName, ignoreCase);
            if (method != null) {
                method.invoke(target, args);
            }
    
        }
    }
    

    最后在mybatis-config.xml里启用该插件:

        <plugins>
            ...
    
            <plugin interceptor="com.xxx.DataChangeLastTimeInterceptor">
            </plugin>
        </plugins>
    

      

  • 相关阅读:
    WPF多线程问题
    SQL 使用经验
    [转]express 路由控制--next
    [转]浅谈Web缓存
    [转]一份优秀的前端开发工程师简历是怎么样的?
    http
    [转]HTTP详解(1)-工作原理
    [转]使用Flexible实现手淘H5页面的终端适配
    [转]理解$watch ,$apply 和 $digest --- 理解数据绑定过程
    GMT时间
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/tk-mybatis-updateByPrimaryKeySelective-with-on-update-problem.html
Copyright © 2020-2023  润新知