环境:Java8、Spring Boot 2.2.10.RELEASE、MyBatis3.5.5、sharding-sphere4.1.1
实体对象有个字段是LocalDateTime在保存时没有任何问题。在查询时会报如下错误:
红色框对应的方法:
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws sql Exception {
return rs.getObject(columnName, LocalDateTime.class);
}
也就是这里针对LocalDateTime数据类型当前的jdbc不支持rs.getObject(columnName, LocalDateTime.class);这种写法。
LocalDateTime、LocalDate这些个日期类型是Java8开始才有的,而这些数据类型是需要JDBC4.2版本才开始支持的也就是JDBC4.2版本才开始支持JSR-310中的对象。
再看shardingsphere我用的版本是4.1.1根据官方版本发行说明从4.1.0就支持java8了啊
是我哪里没有用对还是哪里理解错误了?望高人告知
解决方法:
自定义LocalDateTime类型转换,直接参考当前的LocalDateTimeTypeHandler
package com.pack.ss.config;
import java.sql.CallableStatement;
import java.sql. PreparedStatement ;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;
import com.github.pagehelper.StringUtil;
@Component
@MappedTypes(LocalDateTime.class)
@MappedJdbcTypes(value = JdbcType.TIMESTAMP, includeNullJdbcType = true)
public class MyLocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@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 {
String target = rs.getString(columnName);
if (StringUtil.isEmpty(target)) {
return null;
}
return LocalDateTime.parse(target, dateTimeFormatter);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String target = rs.getString(columnIndex);
if (StringUtil.isEmpty(target)) {
return null;
}
return LocalDateTime.parse(target, dateTimeFormatter);
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String target = cs.getString(columnIndex);
if (StringUtil.isEmpty(target)) {
return null;
}
return LocalDateTime.parse(target, dateTimeFormatter);
}
}
注意getNullableResult方法。到此问题解决了
完毕!!!