Hibernate二进制或大文件类型数据和Oracle交互

//测试存储二进制文件
 @Test
 public void test() throws IOException{
  InputStream in=new FileInputStream("E:\\test.txt");
  byte[] tblob=new byte[in.available()];
  in.read(tblob);
  in.close();
  Session ses = HibernateSessionFactory.getSession();
  System.out.println(ses.hashCode());
  ses.beginTransaction();
  Bigobject bb=new Bigobject("测试大文本", tblob);
  ses.save(bb);
  ses.getTransaction().commit();
  ses.close();
 }
 //测试读取二进制文件
 @Test
 public void readTest() throws IOException{
  Session ses = HibernateSessionFactory.getSession();
  Bigobject bigobject = (Bigobject) ses.get(Bigobject.class, 42);
  System.out.println(bigobject.getTclob());
  if(bigobject.getTblob()!=null){
   OutputStream os=new FileOutputStream("E:\\readbat.txt");
   os.write(bigobject.getTblob());
   os.close();
  }
  
 }
 //测试Blob和Clob类型
 @Test
 public void test1() throws Exception{
  Session ses=HibernateSessionFactory.getSession();
  ses.beginTransaction();
  Bigobject bob=new Bigobject();
  bob.setTclob(ses.getLobHelper().createClob(" "));//保存一个空的Clob实例
  bob.setTblob(ses.getLobHelper().createBlob(new byte[1]));//保存一个空的Blob实例
  ses.save(bob);//保存对象
  ses.flush();//刷新缓存
  ses.refresh(bob,LockMode.UPGRADE);//锁定记录
  if(bob.getTclob()!=null){
   Writer writer=bob.getTclob().setCharacterStream(0);
   writer.write("记不住啊");
   writer.close();
  }
  if(bob.getTblob()!=null){
   InputStream in=new FileInputStream("E:\\ceshi.txt");
   byte[] byteArray=new byte[in.available()];
   in.read(byteArray);
   in.close();
   //把文件中的二进制数据写到Blob对象中
   OutputStream os=bob.getTblob().setBinaryStream(1L);
   os.write(byteArray);
   os.close();
  }
  ses.getTransaction().commit();
  ses.close();
  
 }
 //测试Blob和Clob类型  从数据库读到硬盘
 @Test
 public void test2() throws Exception{
  Session ses=HibernateSessionFactory.getSession();
  Bigobject obj = (Bigobject) ses.get(Bigobject.class, 59);
  if(obj.getTclob()!=null){
   Reader reader=obj.getTclob().getCharacterStream();
   char[] cha=new char[1];
   StringBuilder sb=new StringBuilder();
   while(reader.read(cha)!=-1){
    sb.append(new String(cha));
   }
   System.out.println(sb.toString().trim());
   reader.close();
  }
  if(obj.getTblob()!=null){
   InputStream in=obj.getTblob().getBinaryStream();
   OutputStream os=new FileOutputStream("E:\\aaa.txt");
   int len=-1;
   while((len=in.read())!=-1){
    os.write(len);
   }
  }
    ses.close();
  
 }

上一篇:vue-router传递参数的几种方式


下一篇:Hanoi T note