On Mon, Nov 30, 2009 at 9:57 PM, Base <[email protected]> wrote:
> Hi
>
> I have a database that has a table with complex java objects stored in
> a binary field.
>
> In java i would do something like:
>
> protected Object read(byte[] buf){
> Object obj = null;
> if (buf==null) return obj;
> try {
> ObjectInputStream objectIn =
> new ObjectInputStream(
> new ByteArrayInputStream(buf));
> obj = objectIn.readObject();
> } catch (IOException e){
> ...
> }
> return obj;
> }
>
>
> I am stumped as to how to handle this sort of syntax in clojure.
>
> (defn select-test2[]
> (with-connection db
> (with-query-results res ["SELECT BIN_OBJ FROM MYTABLE where ID
> =16000254"] (doall res))))
>
There seems to be some sort of disconnect here. The second piece of code
queries a database and realizes the result seq. The first extracts a
serialized Java object from a byte buffer. The missing link would be however
one extracts a BLOB from the result seq in the form of a Java byte buffer.
As for the clojure syntax, that for obtaining the byte buffer is unknown,
but presumably involves Java interop. That for the deserialization is
straightforward:
(if-not (nil? byte-buffer)
(with-open [object-in (ObjectInputStream.
(ByteArrayInputStream. byte-buffer))]
(.readObject object-in)))
(Just four lines of Clojure code, versus 11 of Java. :))
(If your Java try block didn't just clean up the streams but also e.g.
logged the error you'll need a try form added, e.g.
(if-not (nil? byte-buffer)
(try
(with-open [object-in (ObjectInputStream.
(ByteArrayInputStream. byte-buffer))]
(.readObject object-in))
(catch (Throwable t)
(log-error t)
(throw t))))
or perhaps more specific handling of particular exceptions.)
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en