myBatis之Clob & Blob
Posted blue星空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了myBatis之Clob & Blob相关的知识,希望对你有一定的参考价值。
1. 表结构
1.1 在mysql中的数据类型,longblob --> blob, longtext --> clob
2. 配置文件, 请参考 myBatis之入门示例
3. LOB.java
package com.blueStarWei.entity; public class LOB { private Integer id; private byte[] picture;//BLOb --> byte[] private String remark;//CLOB --> String //getter & setter method
//toString{No picture}
}
3.1 在Java中数据类型: byte[] --> BLOb , String --> CLOB
4. LOBMapper.java
package com.blueStarWei.mappers; import com.blueStarWei.entity.LOB; public interface LOBMapper { void insert(LOB lob); LOB getLOBByID(Integer id); }
5. LOBMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.blueStarWei.mappers.LOBMapper"> <insert id="insert" parameterType="LOB"> insert into t_lob values(null,#{picture},#{remark}); </insert> <select id="getLOBByID" parameterType="Integer" resultMap="LobResult"> select * from t_lob where id = #{id}; </select> <resultMap type="LOB" id="LobResult"> <id property="id" column="id"/> <result property="picture" column="picture"/> <result property="remark" column="remark"/> </resultMap> </mapper>
6. TestLOB.java
package com.blueStarWei.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.blueStarWei.entity.LOB; import com.blueStarWei.mappers.LOBMapper; import com.blueStarWei.utils.SqlSessionFactoryUtil; public class TestLOB { @Test public void testInsert() { SqlSession session = SqlSessionFactoryUtil.openSession(); LOBMapper mapper = session.getMapper(LOBMapper.class); LOB lob = new LOB(); lob.setRemark("long text for clob..."); try { FileInputStream in = new FileInputStream(new File("C:/Users/msi/Pictures/Camera Roll/Happy.png")); byte[] picture = new byte[in.available()]; in.read(picture); in.close(); lob.setPicture(picture); } catch (Exception e) { e.printStackTrace(); } mapper.insert(lob); session.commit(); session.close(); } @Test public void testGetLob() { SqlSession session = SqlSessionFactoryUtil.openSession(); LOBMapper mapper = session.getMapper(LOBMapper.class); LOB lob = mapper.getLOBByID(6); System.out.println(lob); byte[] picture = lob.getPicture(); File file = new File("C:/Users/msi/Pictures/Camera Roll/Happy_copy.png"); try { FileOutputStream out = new FileOutputStream(file); out.write(picture); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
7.日志
7.1 表数据
7.2 TestLOB输出
7.3 生成图片
8.总结:
Blob & Clob 就是通过流进行读写操作
更多内容,请访问:http://www.cnblogs.com/BlueStarWei/
以上是关于myBatis之Clob & Blob的主要内容,如果未能解决你的问题,请参考以下文章
解决:oracle+myBatis ResultMap 类型为 map 时,表字段类型有 Long/Blob/Clob 时报错