Mysql存储java对象实例详解
Mysql存储java对象
MySQL 设置字段为blob
保存对象,先将对象序列化为byte[] 使用setObject(byte[]bytes)
ByteArrayOutputStreambaos=newByteArrayOutputStream();
ObjectOutputStreamout=null;
try{
out=newObjectOutputStream(baos);
out.writeObject(java实例对象);
}catch(IOExceptione){
logger.error("msg2Byteserror!",e);
}finally{
try{
out.close();
}catch(IOExceptione){
logger.error("msg2Byteserror!",e);
}
}
returnbaos.toByteArray();
获取对象使用getBytes(),将获取的byte[]反序列化为Java对象
ByteArrayInputStreambais;
ObjectInputStreamin=null;
try{
bais=newByteArrayInputStream(bytes);
in=newObjectInputStream(bais);
return(java类)in.readObject();
}finally{
if(in!=null){
try{
in.close();
}catch(IOExceptione){
logger.error("bytes2Msgerror!",e);
}
}
}
网上的其他方式会有各类问题,请慎用。
包括:
1.设置url参数autoDeserialize=true
2.setObject(java实例对象) 查询
ObjectInputStreamoips=newObjectInputStream(rs.getBinaryStream(1));
ArrayList<String>obb=(java类)oips.readObject();//从流中读取对象
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!