问题
如果使用的是mybatis作为orm框架,那么当从mysql数据库切换到达梦数据库时,使用了LocalDateTime会报错。
Error attempting to get column 'create_time' from result set. Cause: dm.jdbc.driver.DMException: 不支持的接口或功能
根本原因是mybatis在转换LocalDateTime的时候发生了异常
解决办法
/**
* 日期时间处理,适配达梦数据库
*/
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
public LocalDateTimeTypeHandler() {
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
ps.setTimestamp(i, null);
return;
}
ps.setTimestamp(i, Timestamp.valueOf(parameter));
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
if (timestamp == null) {
return null;
}
return timestamp.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);
}
}