您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Hibernate操作Blob数据

2025/10/28 2:55:21发布22次查看
首先看数据库,数据库中新建一个blobtable表,表中有两个字段,一个id(主键)一个picture字段是blob类型字段。然后使用hibernate向该数据库中写入和读取数据 在pojo类中picture属性用的是blob类型数据。 下面看操作源码 package dao;import java.io.file;im
首先看数据库,数据库中新建一个blobtable表,表中有两个字段,一个id(主键)一个picture字段是blob类型字段。然后使用hibernate向该数据库中写入和读取数据
在pojo类中picture属性用的是blob类型数据。
下面看操作源码
package dao;import java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.ioexception;import java.io.inputstream;import java.io.outputstream;import java.math.bigdecimal;import java.sql.blob;import org.hibernate.lobhelper;import org.hibernate.query;import org.hibernate.session;import org.hibernate.transaction;import factory.hibernatesessionfactory;import entity.blobtable;public class blobdao { private session session = null; private transaction tran = null; public blobdao(){ this.session = hibernatesessionfactory.getsession(); } public void saveblob(blobtable bigdate,string path) throws ioexception{ /*inputstream in = this.getclass().getresourceasstream(path); byte[] bytes = new byte[in.available()]; in.read(bytes); in.close();*/ file file = new file(path); fileinputstream fis = new fileinputstream(file); byte[] bytes = new byte[fis.available()]; fis.read(bytes); lobhelper lh = session.getlobhelper(); bigdate.setpicture(lh.createblob(bytes)); tran = session.begintransaction(); try{ session.save(bigdate); tran.commit(); system.out.println(插入成功!); }catch(exception e){ system.out.println(插入失败!); tran.rollback(); }finally{ hibernatesessionfactory.closesession(); fis.close(); } } public void getblob(bigdecimal id,string targetpath) throws exception{ string hql = from blobtable where id = ?; query query = session.createquery(hql); query.setbigdecimal(0, id); blobtable bt = (blobtable) query.uniqueresult(); blob image = bt.getpicture(); inputstream in = image.getbinarystream(); outputstream os = new fileoutputstream(targetpath); int n = -1; while((n=in.read())!=-1){ os.write(n); } in.close(); os.close(); }}
package test;import java.io.ioexception;import java.math.bigdecimal;import dao.blobdao;import entity.blobtable;public class test { public static void main(string[] args) { blobdao bb = new blobdao(); blobtable bt = new blobtable(); bt.setid(new bigdecimal(5)); try { string path = f:\\a.jpg; bb.saveblob(bt, path); } catch (ioexception e) { e.printstacktrace(); } blobdao bd = new blobdao(); try { bd.getblob(new bigdecimal(1), e:\\a.jpg); system.out.println(写出成功!); } catch (exception e) { e.printstacktrace(); } }}
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product