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 obb = (java类)oips.readobject();//从流中读取对象
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
希望与广大网友互动??
点此进行留言吧!