欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

迁移达梦数据库适配LocalDateTime

程序员文章站 2022-06-03 11:50:38
...

达梦数据库兼容LocalDateTime

问题

如果使用的是mybatis作为orm框架,那么当从mysql数据库切换到达梦数据库时,使用了LocalDateTime会报错。

Error attempting to get column 'create_time' from result set. Cause: dm.jdbc.driver.DMException: 不支持的接口或功能

根本原因是mybatis在转换LocalDateTime的时候发生了异常

解决办法

/**
 * 日期时间处理,适配达梦数据库
 */
@MappedTypes(LocalDateTime.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class LocalDateTimeTypeHandler implements TypeHandler<LocalDateTime> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, LocalDateTime localDateTime, JdbcType jdbcType) throws SQLException {
        preparedStatement.setTimestamp(i, Timestamp.valueOf(localDateTime));
    }

    @Override
    public LocalDateTime getResult(ResultSet resultSet, String columnName) throws SQLException {
        Timestamp timestamp = resultSet.getTimestamp(columnName);
        return timestamp.toLocalDateTime();
    }

    @Override
    public LocalDateTime getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return resultSet.getTimestamp(columnIndex).toLocalDateTime();
    }

    @Override
    public LocalDateTime getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return callableStatement.getTimestamp(columnIndex).toLocalDateTime();
    }
}

全局注册TypeHandler

@Component
public class CustomTypeHandlerParser implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //从spring容器获取sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
        //获取typeHandler注册器
        TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
        //注册typeHandler
        typeHandlerRegistry.register(LocalDateTime.class, LocalDateTimeTypeHandler.class);
    }
}

参考

  1. Mybatis类型处理器
  2. 达梦数据库迁移