MySQL 设置字段为 blob , java对象实现Serializable接口

  • 保存对象 先将对象转为byte[] (之后序列化到数据库中)
  • 获取对象 (先从数据库中反序列化读出byte[]) 将获取的byte[]转为Java对象

具体实现

  • 保存对象,先将对象序列化为byte[]

    public static byte[] getBytes (java对象) { 
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();    
    	 OutputStream oos = null;     
    	try {       
    	    oos = new  OutputStream(baos);       
    	    oos.write (java对象);     
    	} catch (IOException e) {       
    	    e.printStackTrace();    
    	}finally{       
    	    try {         
    	        oos.close();       
    	    } catch (IOException e) {         
    	        e.printStackTrace();       
    	    }     
    	}          
    	return baos.toByteArray(); 
    }
    
  • 获取对象 将反序列化获取的byte[]转为Java 对象

    public static java对象类型 getObj (byte[] data) {
    	ByteArrayInputStream bais;     
    	 InputStream ois = null;     
    	try{       
    	    bais = new ByteArrayInputStream(data);       
    	    ois = new  InputStream(bais);         
    	    return (java对象类型)ois.read ();     
    	}finally{       
    	    if(ois != null){         
    	        try {           
    	            ois.close();         
    	        } catch (IOException e) {           
    	            e.printStackTrace();          
    	        }       
    	    }     
    	} 
    }
    

网上的其他方式会有各类问题,慎用。(借鉴)

包括:

  • 1.设置url参数
    • autoDeserialize=true
  • 2.set (java实例对象)
    • InputStream oips = new InputStrea(rs.getBinaryStream(1));
    • ArrayList obb = (java类)oips.read ();//从流中读取对象
收藏 打印