Mybatis读取Blob字段图片

1. 在mapper的resultMap中定义对应列

1
2
3
4
<resultMap id="queryBlobCloum" type="PicVO(指向vo类)">
<result column="uuid" property="uuid" jdbcType="VARCHAR" />
<result column="pic" property="pic" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
</resultMap>

2. 定义接收blob的vo类

采用byte[]方式接收blob字段

1
2
3
4
5
@Data
public class PicVO {
private String uuid;
private byte[] pic;
}

3. select调用resultmap

1
2
3
<select id="readPic" resultMap="queryBlobCloum">
SELECT uuid,pic(Blob格式字段) FROM table
</select>

4. 用文件流保存对应的byte[]字段

1
2
3
4
5
6
7
8
9
10
11
12
InputStream in = new ByteArrayInputStream(picture);
String picName = "E:/pic/" + uuid + ".png";
System.out.println(picName);
OutputStream out = new FileOutputStream(picName);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
in.close();
out.close();