First look at the database, a new blobtable table in the database, the table has two fields, an ID (primary key) a picture field is a blob type field. Then use hibernate to write and read data to the database
In the Pojo class, the Picture property uses BLOB type data.
See below Operation source code
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.sessi On = 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 ("Insert succeeded! ");} catch (Exception e) {System.out.println ("Insert failed! "); 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 (I Oexception e) {e.printstacktrace ();} Blobdao bd = new Blobdao (); try {Bd.getblob (new BigDecimal (1), "e:\\a.jpg"); System.out.println ("Write success!") ");} catch (Exception e) {e.printstacktrace ();}}}
Hibernate manipulating BLOB data