hibernate 将图片写入 oracle blob

用JDBC操作Blob最基本的思路是:先插入一条包含空Blob的记录,然后立即将该条记录用行锁定的方式打开,得到改Blob字段的引用,从中得到一个输出流,将byte[]数据写入后提交。hibernate操作的基本思路也是一致的。

 

参考url:

http://biekwo.iteye.com/blog/323393

http://bbs.csdn.net/topics/60009941

 

由于如果不是使用oracle 操作 blob,会报 不支持新特性的错误

 

robbin的这篇也可以

http://www.iteye.com/topic/254

 

这是另一个思路,但是我没有试验成功

http://bbs.csdn.net/topics/220063661

 

如果报这个错误

不允许的操作: streams type cannot be used in batching

参考这个url

http://hsyd.iteye.com/blog/320579

 

我的代码

 1 publicint add(User u) {
 2 
 3 // TODO Auto-generated method stub
 4 
 5 try{
 6 
 7 //获取数据id
 8 
 9  
10 
11 u.setId(GetMax());
12 //空的blob
13 u.setImage(Hibernate.createBlob(newbyte[1]));
14 Session session = sessionFactory.openSession();
15 
16 transaction = session.beginTransaction();
17 session.save(u);
18 
19 session.flush();
20 
21 session.refresh(u,LockMode.UPGRADE);
22 
23 //获取引用
24 
25 SerializableBlob sb = (SerializableBlob)u.getImage(); 
26 
27 BLOB blob = (oracle.sql.BLOB)sb.getWrappedBlob();  
28 
29 OutputStream out =((oracle.sql.BLOB)blob).getBinaryOutputStream(0);
30 
31  
32 
33  
34 
35 File file = new File("/Users/apple/Downloads/project.png"); 
36 
37 FileInputStream fis = new FileInputStream(file); 
38 
39     byte[] buff = newbyte[fis.available()]; 
40 
41     fis.read(buff); 
42 
43     fis.close(); 
44 
45     out.write(buff); 
46 
47     out.close();
48 
49  
50 
51 // When done close the streams
52 
53  
54 
55 //
56 
57 session.flush();
58 
59 //
60 
61 transaction.commit();
62 
63 System.out.println("save success");
64 
65 }catch(Exception e){
66 
67 System.out.println(e.getMessage());
68 
69 return 0;
70 
71 }
72 
73 return 1;
74 
75 }

 

 

posted @ 2012-12-30 17:44  CowboyRyan  阅读(1423)  评论(0编辑  收藏  举报