sql报错Error attempting to get column ‘create_time’ from result set. Cause: java.sql.SQLFeatureNotSupported
1.发生背景
项目开发过程中一直适配的是mysql5.7版本,忽然要求改成适配mysql8,在执行sql命令时报错
2.报错分析
select id,creator_id,create_time,update_id,update_time from ent_table where (id = '8656261875367936' )
字段名称 | 字段类型 |
---|---|
id | varchar |
creator_id | varchar |
create_time | datetime |
update_id | varchar |
update_time | datetime |
可以看出sql比较简单,在数据库中也能正常执行,问题出现的原因在mybatis进行数据转换上,因为我的表的createtime类型为datetime,通过mybatis-plus代码生成器生成的是LocalDateTime,而Java8里面新出来了一些API,LocalDate、LocalTime、LocalDateTime ,但是在默认的情况下,在mybatis里面不支持java8的时间、日期,因此在下列源码的getNullableResult方法中转换报错。
/**
* Copyright 2009-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
/**
* @since 3.4.5
* @author Tomas Rohovsky
*/
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
throws SQLException {
ps.setObject(i, parameter);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
// 报错代码行
return rs.getObject(columnName, LocalDateTime.class);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getObject(columnIndex, LocalDateTime.class);
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getObject(columnIndex, LocalDateTime.class);
}
}
3.解决方案
- 修改数据库字段由datetime为date类型
修改后能正常执行sql
字段名称 | 字段类型 |
---|---|
id | varchar |
creator_id | varchar |
create_time | date |
update_id | varchar |
update_time | date |
-
重写mybatis的LocalDateTimeTypeHandler,既然是转换报错,则修改相应的转换类处理方法
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> { ... @Override public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { return LocalDateTime.parse(rs.getObject(columnName).toString()); } ... }