dT*blog

design and programming

直列化したデータをDBに突っ込む

シリアライズしたオブジェクトは、DBのバイナリデータ型のカラムに登録することができる。生成にコストがかかって、かつセッションに保持するとメモリを食い潰しそうなオブジェクトの保存方法のひとつとして、この手段を検討したい。

Connection conn = null;
PreparedStatement ps = null;

// 指定オブジェクトを直列化 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject((Serializable) contents); int buffer = baos.size();
// DBへの書き出し用ストリームの作成 InputStream in = new ByteArrayInputStream(baos.toByteArray());
// 直列化したオブジェクトを InputStream に書出 baos.flush();
try { String sql = "INSERT INTO table(contents) VALUES (?)"; conn = getConnection(); ps = conn.parepareStatement(sql); ps.setBinaryStream(1, in, buffer); ps.executeUpdate } catch (Exception e) { e.printStackTrace(); } finally { if (ps != null) ps.close(); if (conn != null) conn.close(); }

サンプルとしてざっくり書いてみたけど、こんな感じで大丈夫のはず。とりあえずメモなんで、動かしてないです。間違いあったら、すんません。

ちなみに、ByteArrayOutputStream の close には意味が無いらしい。転送先にデータを書き出すためには、明示的に flush する必要があるとのこと。標準APIのjavadocに書いてあったので、多分そうなんだと思います。(おいおい)

Posted by dT by 19:35

トラックバック

このエントリーのトラックバックURL
http://www.deftrash.com/admin/mt/mt-tb.cgi/372

コメント




保存しますか?

(書式を変更するような一部のHTMLタグを使うことができます)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30