案例: 收到的request資料中一個JSON格式的資料要保存,但為何不存JSON的字串就好?因為這個資料會不斷變動的,所以收到變動只要取出這個已將JSON轉成list的添加或刪除東西就好,不用再將JSON轉成list再轉回JSON存到DB去。
在Hibernate中是設定該欄位為type="java.sql.Blob",會自動在Mysql中建成DataType為LONGBLOB
下面是把JSON轉成list後,轉成blob型態存入DB
ObjectMapper mapper = new ObjectMapper();//用Jackson處理JSON
Blob blob = null;
try {
SongResp dto = mapper.readValue(json, SongResp.class);
List list = dto.getSongs();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(list);
bout.close();
oos.close();
byte[] asBytes = bout.toByteArray();
blob = Hibernate.createBlob(asBytes);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
以下是把DB中的該欄位取出成當時寫入的list
List list;
Blob b = userDao.getUserData(id, dataType);
try {
if (b != null) {
InputStream in = b.getBinaryStream();
ObjectInputStream ooi = new ObjectInputStream(in);
in.close();
ooi.close();
list = (List)ooi.readObject();
return list;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}