日期:2014-05-20 浏览次数:20920 次
package com.xl.vo; import java.sql.Blob; import java.sql.Clob; /** * Userinfo entity. * * @author MyEclipse Persistence Tools */ public class Userinfo implements java.io.Serializable { // Fields private Integer id; private Blob faceimag; private Clob remark; // Constructors /** default constructor */ public Userinfo() { } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Blob getFaceimag() { return this.faceimag; } public void setFaceimag(Blob faceimag) { this.faceimag = faceimag; } public Clob getRemark() { return this.remark; } public void setRemark(Clob remark) { this.remark = remark; } }
package com.xl.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.Clob; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import com.xl.se.HibernateSessionFactory; import com.xl.vo.Userinfo; public class Text { /** * @param args */ private static Session session = HibernateSessionFactory.getSession(); public static void main(String[] args) { //如果不执行insert()那么就将一切正常~~~ String filePath = new File("bin").getAbsolutePath()+"\\image\\1.jpg"; insert(filePath); System.out.print("插入成功!"); reader(); } private static void insert(String filePath){ try { FileInputStream file = new FileInputStream(filePath); Blob blob = Hibernate.createBlob(file); Userinfo user = new Userinfo(); user.setFaceimag(blob); Clob clob = Hibernate.createClob("This is Clob DataType"); user.setRemark(clob); Transaction tra = session.beginTransaction(); session.save(user); tra.commit(); file.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void reader(){ try { InputStream is = null; FileOutputStream file = null; List list = session.createQuery("from Userinfo").list(); Iterator it = list.iterator(); int count = 0; while(it.hasNext()){ count++; System.out.println(count); Userinfo user = (Userinfo)it.next(); int id = user.getId(); Clob clob = user.getRemark(); String remark = clob.getSubString(1, (int)clob.length());//这句话报异常 System.out.println(remark); Blob blob = user.getFaceimag(); is = blob.getBinaryStream(); file = new FileOutputStream("d://"+count+".jpg"); byte [] bytes = new byte[1024]; int len; while((len = is.read(bytes)) != -1){ file.write(bytes); } } is.close(); file.flush(); file.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }