1、在pojo类中 用Blob类和Clob

1
2
3
4
5
6
7
8
9
public class Student {
private int id;
private String name;
private int age;
//存放大数据 可以存放4G的内容
private Blob image;
private Clob introduce;
//省略get/set
}

2、在hbm文件中,需指定对应类型

1
2
3
4
5
6
7
8
9
10
11
<hibernate-mapping package="cn.siggy.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、 构造对象, 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Test
public void testSave() throws HibernateException, SerialException, SQLException{
Session session = null;
Transaction tx = null;
try{
session = HibernateUtil.getSession();
tx = session.beginTransaction();
Student stu = new Student();
stu.setName("尹志平");
stu.setAge(23);

Blob blob = new SerialBlob("ttt".getBytes());
Clob clob = new SerialClob("sss".toCharArray());
stu.setImage(blob);
stu.setIntroduce(clob);
session.save(stu);

tx.commit();

}catch (HibernateException e) {
if(tx!=null)
tx.rollback();
e.printStackTrace();
throw e;
}finally{
HibernateUtil.closeSession();
}
}