Just playing around is one of my favorite ways of becoming familiar with software. Let’s see how we can use the BeanShell to prototype Hibernate. I’m partial towards the BeanShell because it’s embedded in my Java Development Environment for Emacs. But if you’re so inclined, then Jython will probably do as well. Just in case there is a lurking configuration gotcha, here’s my current Java software configuration.
I must confess that I wasn’t planning on using the BeanShell. I was planning on adding a simple interpreter with java.io.StreamTokenizer to allow interactive manipulation of Keyword and KeySet objects. And then I realized that by setting the fork attribute of the java task to true separated my application from the console input. And setting it to false terminates the application with an java.lang.ExceptionInInitializerError. The BeanShell was my ticket out.
BeanShell support requires just a handfull of minor changes to our build file. First, the BSH property is added to reference the BeanShell jar and it is prepended to classpath.run to form classpath.bsh. Second, a new bsh target is added in parallel to the run target — note that we use class bsh.Console rather than bsh.Interpreter because we still lose access to console input because of the JVM fork. And Finally, the dist target was modified to include a bsh sub-directory.
Next, we’ll create a Scripted Object to simplify our interaction with hibernate. The Hibernate method returns an object that provides easy access to the most common functionality: open, save, find, delete and close.
Finally, two methods were added each of the KeySet and Keyword classes. The KeySet class gained an add and a remove method that simply provide access to the corresponding methods of the java.util.Set member variable. And the Keyword class gained methods for hashCode and equals — this insures that Keyword objects are equivalent when their String member variables are equivalent.
And now we’re ready to play with the BeanShell (starting with an empty database). By the way, if you’re anything like me, then the number one thing to remember is use print rather than println.
We can use the BeanShell to see that we
cannot use Hibernate for immutable objects need to be careful when comparing objects from different sessions:
We also see that Hibernate performs a shallow save rather than a deep save:
21 May 2004: This behavior is controlled by the cascade attribute.
We’re done for now. You’re ready to download the source to prototype Hibernate with the BeanShell and play.
Disclaimer: I don’t claim to be an expert on hibernate. Please send comments and corrections.