mybaties连接sqlite,并读取blob类型数据时,报 java.sql.SQLException: not implemented by SQLite JDBC driver错误
由于某些原因,不能共开公司代码,这里是自用代码片段
场景:
具体需求,要求像springboot连接mysql或者pgsql数据库一样,在application配置文件中配置sqlite数据库信息,并实现对blob类型数据(我们的库中有该类型的数据)的读写,按照平常一样写好controller、service、dao、mapper.xml后,执行查询操作后报错
原因分析:
sqlite的driver中,JDBC4ResultSet没有实现以下接口:
public Blob getBlob(int col)
throws SQLException { throw unused(); }
public Blob getBlob(String col)
throws SQLException { throw unused(); }
而是直接抛出了异常。
解决方法:
mapper.xml中该字段的设置:
<select id="queryByList" resultMap="queryBaseResultMap">
select * from my_blob
</select>
<resultMap id="queryBaseResultMap" type="com.wx.model.MyBlob" >
<id column="Id" property="id" jdbcType="INTEGER" />
<result column="blob" property="blob" typeHandler="com.wx.handler.BlobTypeHandler"/>
</resultMap>
即blob字段加个typeHandler属性。
然后自定义一个BlobTypeHandler处理类:
public class BlobTypeHandler extends BaseTypeHandler<byte[]> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, byte[] parameter, JdbcType jdbcType) throws SQLException {
ps.setBytes(i, parameter);
}
@Override
public byte[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getBytes(columnName);
}
@Override
public byte[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getBytes(columnIndex);
}
@Override
public byte[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getBytes(columnIndex);
}
}
注意:实体类中blob字段类型是byte[]
这样就可以查到blob类型的数据了,具体要将blob类型的数据保存到文件中还是怎样,请自行根据业务处理。
参考文章:
https://blog.csdn.net/icyfox_bupt/article/details/108867782
https://blog.csdn.net/jingtianyiyi/article/details/80421930
https://blog.csdn.net/gouwenyu/article/details/50327401