以学生类为例,有这样一种场景,假如有学生的头像、简介里面的值可能很大,通常情况下都是通过文件上传存到服务器上,数据库只放在服务器的地址即可但是现在我不想将信息放入磁盘,而是直接存入数据库中,这个时候就用到了Blob和Clob。通过下面的案例来简单了解下这两个对象在hibernate中的使用吧。
1、在Student类中使用Blob(数据文件、图像、视频类型)和Clob(字符串文件类型)
public class Student {
private int id;
private String name;
private int age;
//存放大数据 可以存放4G的内容
private Blob image;
private Clob introduce;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/**
*省略其他属性的get/set方法
**/
}
2、在Student.hbm.xml映射文件中指定对应类型
<hibernate-mapping package="com.test.pojo">
<class name="Student">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name" />
<property name="age" />
<property name="image" type="java.sql.Blob"/>
<property name="introduce" type="java.sql.Clob"/>
</class>
</hibernate-mapping>
3、构造对象,测试
public class HibernateTest {
@Test
public void testCreateDB(){
Configuration cfg=new Configuration().configure();
SchemaExport se=new SchemaExport(cfg);
//第一个参数表示是否生成ddl脚本,第二个参数表示是否执行到数据库中
se.create(true, true);
}
/**
* 保存数据
*/
@Test
public void save(){
Session session=null;
Transaction tx=null;
try{
session=HibernateUtil.getSession();
tx=session.beginTransaction();
Student stu=new Student();
stu.setName("楚乔");
stu.setAge(18);
Blob blob=new SerialBlob("ttt".getBytes());
Clob clob=new SerialClob("sss".toCharArray());
stu.setImage(blob);
stu.setIntroduce(clob);
session.save(stu);
tx.commit();
}catch(Exception e){
if(tx!=null)
tx.rollback();
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
}
运行testCreateDB控制台打印如下信息:
执行save方法,控制台打印如下信息: