hibernate对 oracle 的blob数据类型的处理

oracle数据库建表语句

create table stu
(
id number(2),
name varchar2(16),
filename varchar2(64),
filedata BLOB,
primary key(id)
);

Stu.java文件

public class Stu implements java.io.Serializable {

// Fields

private Byte id;
private String name;
private String filename;
private byte[] filedata; //此处理将其属性类型设为byte[]

// Constructors

/** default constructor */
public Stu() {
}

剩余部分略去.....

Stu.hbm.xml文件如下:

<hibernate-mapping>
<class name="com.aoyou.mapping.Stu" table="STU" schema="LIXIN03080">
<id name="id" type="java.lang.Byte">
<column name="ID" precision="2" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="16" />
</property>
<property name="filename" type="java.lang.String">
<column name="FILENAME" length="64" />
</property>

<hibernate-mapping>
<class name="com.aoyou.mapping.Stu" table="STU" schema="LIXIN03080">
<id name="id" type="java.lang.Byte">
<column name="ID" precision="2" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="16" />
</property>
<property name="filename" type="java.lang.String">
<column name="FILENAME" length="64" />
</property>
<!-- 注意下面filedata的type为binary -->
<property name="filedata" type="binary">
<column name="FILEDATA" />
</property>
</class>
</hibernate-mapping>
<property name="filedata" type="binary">
<column name="FILEDATA" />
</property>
</class>
</hibernate-mapping>

在main方法中测试:

保存数据到数据库:

public static void main(String[] args) throws IOException{
Session session = new Configuration().configure().buildSessionFactory().openSession();
Transaction t = session.beginTransaction();

File file = new File("D:\\购物网站\\二期\\数据库设计.txt");
BufferedReader br = new BufferedReader(new FileReader(file));


Stu stu = new Stu();
stu.setId(2);
stu.setName("mary");
stu.setFilename("数据清单");

String content = "";
String temp = "";
while((temp = br.readLine()) != null){
content += temp;
}
br.close();
stu.setFiledata(content.getBytes());
session.save(stu);

t.commit();
}

读取数据库数据:

public static void main(String[] args) throws IOException{
Session session = new Configuration().configure().buildSessionFactory().openSession();
Transaction t = session.beginTransaction();

String hql = " from Stu ";
Query query = session.createQuery(hql);
List list = query.list();
if(list != null){
Stu stu = (Stu)list.get(0);
System.out.println(stu.getId());
System.out.println(stu.getName());
System.out.println(stu.getFilename());
byte[] b = stu.getFiledata();
System.out.print(new String(b, 0, b.length));
}

t.commit();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值