MybatisPlus+SQLite 中无法读BLOB类型数据问题
一、问题描述
对 BLOB 类型操作时,写入可以成功,但是读取失败。
@TableName public class Demo { private byte[] data; }
执行读取操作时报错如下:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessApiUsageException: Error attempting to get column data from result set. Cause: java.sql.SQLFeatureNotSupportedException: not implemented by SQLite JDBC driver ; not implemented by SQLite JDBC driver] with root cause java.sql.SQLFeatureNotSupportedException: not implemented by SQLite JDBC driver
二、原因
对于 BLOB 的读取,在 JDBC 规范中有 3 种接口:
-
InputStream getBinaryStream(int col) byte[] getBytes(int col) Blob getBlob(int col)
而 Mybatis Plus 默认会选择第 3 个接口。 因此只需要通过设置 TypeHandler 修改处理方式即可。
三、解决方法
- autoResultMap 属性设置为 true
- 添加 @TableField(typeHandler = ByteArrayTypeHandler.class)
@TableName(autoResultMap = true) public class Demo { @TableField(typeHandler = ByteArrayTypeHandler.class) private byte[] data; }
而对于用 XML 实现的 SQL 需要通过以下方式设置 typeHandler:
<resultMap id="DemoMap" type="Demo" > <result column="data" property="data" typeHandler="org.apache.ibatis.type.ByteArrayTypeHandler"/> </resultMap> <select id="search" resultMap="ResourceMap"> <!-- sql --> </select>