加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Mysql存储java对象实例详解

发布时间:2020-12-14 14:44:16 所属栏目:Java 来源:网络整理
导读:Mysql存储java对象 MySQL 设置字段为 blob 保存对象,先将对象序列化为byte[] 使用 setObject(byte[] bytes) ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = null; try { out = new ObjectOutputStream(baos); out.wr

Mysql存储java对象

MySQL  设置字段为 blob

保存对象,先将对象序列化为byte[]  使用 setObject(byte[] bytes)

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ObjectOutputStream out = null; 
    try { 
      out = new ObjectOutputStream(baos); 
      out.writeObject(java实例对象);    
    } catch (IOException e) { 
      logger.error("msg2Bytes error!",e); 
    }finally{ 
      try { 
        out.close(); 
      } catch (IOException e) { 
        logger.error("msg2Bytes error!",e); 
      } 
    } 
     
    return baos.toByteArray(); 

获取对象 使用getBytes(),将获取的byte[]反序列化为Java 对象

ByteArrayInputStream bais; 
    ObjectInputStream in = null; 
    try{ 
      bais = new ByteArrayInputStream(bytes); 
      in = new ObjectInputStream(bais); 
 
      return (java类)in.readObject(); 
    }finally{ 
      if(in != null){ 
        try { 
          in.close(); 
        } catch (IOException e) { 
          logger.error("bytes2Msg error!",e); 
        } 
      } 
    } 

网上的其他方式会有各类问题,请慎用。

包括:

1.设置url参数 autoDeserialize=true
2.setObject(java实例对象)        查询

ObjectInputStream oips = new ObjectInputStream(rs.getBinaryStream(1)); 
ArrayList<String> obb = (java类)oips.readObject();//从流中读取对象 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读