Mybatis 处理 CLOB/BLOB 类型数据

42 篇文章 0 订阅
1 篇文章 0 订阅

Mybatis 处理 CLOB/BLOB 类型数据

BLOB 和 CLOB 都是大型字段类型。

BLOB通过二进制存储,而CLOB可以直接存储文本。

通常,图片、文件、音乐等信息存储在 BLOB 字段中。首先,文件是转换为二进制,然后存储在。文章或较长的文本存储在 CLOB 中。

不同数据库中相应的 BLOB 和 CLOB 类型也不同:

在MySQL中,clob对应于text/longtext,blob对应于blob。

在Oracle中:clob 对应于 clob,blob 对应于 blob。

MyBatis 为 CLOB/BLOB 类型的列提供了内置的映射支持。

1、创建表语句:

create table user_pics(
	id number primary key,
	name varchar2(50) ,
	pic blob,
	bio clob
);

2、图片(PICS)可以是PNG,JPG或其他格式。简要信息(bio)可以是很长的文本描述。默认情况下,MyBatis 将 CLOB 列映射到 java.lang.String 类型,将 BLOB 列映射到 byte [] 类型。

public class UserPic{
	private int id;
	private String name;
	private byte[] pic;
	private String bio;
	//setters & getters
}

3、Map 文件:

<insert id="insertUserPic" parameterType="UserPic">
	<selectKey keyProperty="id" resultType="int" order="BEFORE">
	select my_seq.nextval from dual
	</selectKey>
	insert into user_pics(id,name, pic,bio) values(#{id},#{name},#{pic},#{bio})
</insert>

<select id="getUserPicById" parameterType="int" resultType="UserPic">
	select * from user_pics where id=#{id}
</select>

4、Mapping 接口:

public interface PicMapper {
	
	int insertUserPic(UserPic userPic);

	UserPic getUserPicById(int id);
}

5、测试方法:

@Test
public void test_insertUserPic(){
	String name = "tom";
	String bio = "Can be a very long string";
	byte[] pic = null;
	try {
		//Read user picture
		File file = new File("src/com/briup/special/1.gif");
		InputStream is = new FileInputStream(file);
		pic = new byte[is.available()];
		is.read(pic);
		is.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	//Prepare the data to be inserted into the database and encapsulate it as an object
	UserPic userPic = new UserPic(name, pic , bio);
	SqlSession sqlSession = null;
	try {
		sqlSession = MyBatisSqlSessionFactory.openSession();
		SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class);
		mapper.insertUserPic(userPic);
		sqlSession.commit();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

6、以下 getUserPic() 方法将 CLOB 类型数据读取为字符串类型,将 BLOB 类型数据读取为字节 []属性:

@Test
public void test_getUserPicById(){
	SqlSession sqlSession = null;
	try {
		sqlSession = MyBatisSqlSessionFactory.openSession();
		SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class);
		UserPic userPic = mapper.getUserPicById(59);
		System.out.println(userPic.getId());
		System.out.println(userPic.getName());
		System.out.println(userPic.getBio());
		System.out.println(userPic.getPic().length);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷彩的博客

你的鼓励将是我最大的创作动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值