在MySQL中保存Java對象

須要在MySQL中保存Java對象。java

說明:code

  • 對象必須實現序列化
  • 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對象it

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;
}
相關文章
相關標籤/搜索