<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>www.jugpadova.it: Tag blob</title>
    <link>http://www.jugpadova.it/articles/tag/blob</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Java User Group [Padova]</description>
    <item>
      <title>Serialize a bean using jdbc</title>
      <description>&lt;p&gt;Sometimes,  in my work as programmer, I need to serialize an object (bean) into a table, in a BLOB field, as well as retrieves bean from a ResultSet.
I have realized a simple example that, using JDBC, allows to obtain this.&lt;/p&gt;
&lt;p&gt;Here the method to fill PreparedStatement :&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_java "&gt;public static void fillPreparedStatement(PreparedStatement pst, int index,
         Serializable obj) throws Exception {

      if (obj != null) {
         ByteArrayOutputStream regStore = new ByteArrayOutputStream();

         ObjectOutputStream regObjectStream = new ObjectOutputStream(regStore);
         regObjectStream.writeObject(obj);
         byte[] regBytes = regStore.toByteArray();
         regObjectStream.close();
         regStore.close();
         ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes);
         pst.setBinaryStream(index, regArrayStream, regBytes.length);
      }// end of if
      else {
         pst.setNull(index, Types.BLOB);
      }
}// end of method
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Here the method to retrieve bean from ResultSet.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_java "&gt;public static Object getFromResultSet(ResultSet rs, String columnName)
         throws Exception {
      byte[] regBytes = rs.getBytes(columnName);
      ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes);
      ObjectInputStream regObjectStream = new ObjectInputStream(
            regArrayStream);
      return regObjectStream.readObject();
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;I tested this code using MySQL 4.1 db.
Hope this example could save your valuable time.
Enrico.&lt;/p&gt;</description>
      <pubDate>Tue, 10 Jan 2006 18:19:00 +0100</pubDate>
      <guid isPermaLink="false">urn:uuid:1c49d880-c8d7-4b47-b75b-3e1dcfc292a2</guid>
      <author>Enrico Giurin</author>
      <link>http://www.jugpadova.it/articles/2006/01/10/serialize-a-bean-using-jdbc</link>
      <category>Tips &amp; Tricks</category>
      <category>blob</category>
      <category>jdbc</category>
      <category>bean</category>
    </item>
  </channel>
</rss>
