环境:mysql8 mybatis
背景:最近在做一个功能时需要对程序生成的对象保存到数据库中。
注意事项:需要存储的对象需要实现序列化接口
例:
import java.io.Serializable; public class Test implements Serializable { //一些属性 ....... }
代码:
实体类:
public class Entity { private String id; ..... //用来存储序列化后的对象 private byte[] blob; //get和set方法 ...... }
写数据库:将字节数组写进数据库,博主在mysql数据库创建相关字段时使用的是Blob类型。
public void writeMysql(Object object) { byte[] bytes = new byte[0]; try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream); outputStream.writeObject(object); bytes = byteArrayOutputStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); } //下面写数据库 。。。。。。 }
读数据库:从数据库中读取blob类型数据,然后使用ObjectInputStream将对象反序列化
public void readMysql(Object object) { // 从数据库中查询出结果 Object mysqlobject = 从数据查询出来的结果; byte[] bytes = (byte[])从mysqlobject中取出存储的序列化对象 ObjectInputStream inputStream = null; inputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object object3 = inputStream.readObject(); //object3就是存储之前的对象,接下来可以对object3强制转换为存储之前的类型,进行其他操作 。。。。。。。 }