posts - 138, comments - 150, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

序列化和反序列化对象到 数据库

Posted on 2007-11-29 17:35 G_G 阅读(817) 评论(1)  编辑  收藏 所属分类: javaGeneral

     /*
     * 将对象转化成java.sql.Blob 
     * 要求 对象是序列化的
     
*/
    
public  java.sql.Blob ObjectToBlob(Object obj)  throws  IOException{
        
try  {
            ByteArrayOutputStream out 
=   new  ByteArrayOutputStream();
            ObjectOutputStream outputStream 
=   new  ObjectOutputStream(out);
            outputStream.writeObject(obj);
            
byte [] bytes  =  out.toByteArray();
            outputStream.close();
            
return  Hibernate.createBlob(bytes);
        } 
catch  (Exception e) {
            
//  TODO: handle exception
            System.out.println( " ObjectToBlob " );
            
return   null ;
        }        
    }
    
    
    
/*
     * 将java.sql.Blob 转化成 对象 相应对象
     * 要求 对象是序列化的
     
*/     
    
public  Object BlobToObject(java.sql.Blob desblob,Object obj)  throws  IOException{
        
try  {
            ObjectInputStream in 
=   new  ObjectInputStream(desblob.getBinaryStream());
            obj 
=   in.readObject();
            in.close();    
            
return  obj;
        } 
catch  (Exception e) {
            
//  TODO: handle exception
            System.out.println( " BlobToObject " );
            e.printStackTrace();
            
return   null ;
        }        
    }    
    
    


Feedback

# re: 序列化和反序列化对象到 数据库  回复  更多评论   

2007-11-29 19:06 by 专注java开源
收藏~



标题  
姓名  
主页
验证码 *  
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交