clob mybatis_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类型列的映射处理支持。

建表语句:

create tableuser_pics(

idnumber primary key,

namevarchar2(50) ,

pic blob,

bio clob

);

照片(pic)可以是PNG,JPG或其他格式的。简介信息(bio)可以是学比较长的文字描述。默认情况下,MyBatis将CLOB类型的列映射到java.lang.String类型上、而把BLOB列映射到byte[]类型上。

public classUserPic{private intid;privateString name;private byte[] pic;privateString bio;//setters & getters

}

映射文件:

select my_seq.nextval from dualinsert into user_pics(id,name, pic,bio)

values(#{id},#{name},#{pic},#{bio})

select * from user_pics where id=#{id}

映射接口:

public interfacePicMapper {intinsertUserPic(UserPic userPic);

UserPic getUserPicById(intid);

}

测试方法:

public voidtest_insertUserPic(){

String name= "tom";

String bio= "可以是很长的字符串";byte[] pic = null;try{//读取用户头像图片

File file = new File("src/com/briup/special/1.gif");

InputStream is= newFileInputStream(file);

pic= new byte[is.available()];

is.read(pic);

is.close();

}catch(Exception e){

e.printStackTrace();

}//准备好要插入到数据库中的数据并封装成对象

UserPic userPic = newUserPic(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();

}

}

下面的getUserPic()方法将CLOB类型数据读取到String类型,BLOB类型数据读取成byte[]属性:

@Testpublic voidtest_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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值