• 在MySQL中保存Java对象


    需要在MySQL中保存Java对象。

    说明:

    • 对象必须实现序列化
    • MySQL中对应字段设置为blob

    将Java对象序列化为byte[]

    public static byte[] obj2byte(Object obj) throws Exception {
        byte[] ret = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(obj);
        out.close();
        ret = baos.toByteArray();
        baos.close();
        return ret;
    }
    

    将byte[]反序列化为Java对象

    public static Object byte2obj(byte[] bytes) throws Exception {
        Object ret = null;
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(bais);
        ret = in.readObject();
        in.close();
        return ret;
    }
    
  • 相关阅读:
    mysql基础(三)
    mysql基础(二)
    Mysql基础(一)
    Less32-Less-33
    Less-27
    Less-26
    Less-25
    Less-23
    Less18-Less19
    Less13-Less-14
  • 原文地址:https://www.cnblogs.com/okokabcd/p/10225165.html
Copyright © 2020-2023  润新知