Thursday, December 24, 2009

Adventures in ORM

I've been spending a little time over the Christmas break working with toolsets I don't usually use. (I think this helps me better appreciate the tools I use, no matter what they are.) For the past couple of days I've been having a look at Java ORM solutions.

I had a quick look at Spring 3 / Hibernate 3, but hit some resistance in the form of strange errors I couldn't easily resolve. Sometimes in this case I'll just dig in and spend as much time as I have to, but in this case I decided to put down this toolkit and pick up another.

I've been doing a little work with the GlassFish application server, so I thought this would be a good chance to pick up NetBeans and make use of some of it's neat features. Every time I see the Sun folks talk, they really make NB look attractive, so I was hoping to find something good there.

Well.... I initially liked what I saw. I already had a PostGres database (also not my usual choice), so I made use of a cool code-gen feature to instantly make some Entity objects. Really easy!

The Entity beans weren't much use without a wrapper class to use them, so I also auto-generated (all this through right-click!) some Controller classes off the Entity beans. Also very easy!

Now just to hand-code a 'Main' and invoke the Controller classes. Much to my chagrin, all my nicely generated code didn't work. What was up?

A quick look at the log showed the query that was generated. Something like this:
select Name, Id from BC_Schema.BowlingCenters

That was a good clue. I knew from running hand-built queries that PostGres preferred something like this:
select "Name", "Id" from "BC_First_Schema"."BowlingCenters"

The difference was only the quotation marks. (Maybe this seems natural to PostGres users. I don't often use it, so it seemed odd to me.)

After quickly searching the web (thanks Google!) I found the quick cure was to doctor up the generated Entity class. Wherever an annotation referenced a keyword in the query, I added a backslash-double-quote to make it print the quotes when it gen'ed the query. Example:

@Column(name = "Id")

Was fixed to be:

@Column(name = "\"Id\"")

After that, I was able to quickly generate Entities and Controllers, building out a db-based application in no time. Very productive!

Probably the most valuable idea I got from the whole adventure was this:

When working with a new ORM setup, start out by coding a plain JDBC snippet to view a few rows. This will convince you you've got your credentials right, allowing you to work with fewer factors as you run down your initial bugs.

Happy Coding, and Merry Christmas!

No comments: