迁移达梦数据库适配LocalDateTime
程序员文章站
2022-06-03 11:50:38
...
问题
如果使用的是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);
}
}
参考
上一篇: Shell基本命令
下一篇: 达梦数据库静默安装的方法