Wednesday, April 21, 2010

Eclipse Generates it, you fix it.

Lesson learned...

So as I continue my mad scientist like exploration of JPA, specifically EclipseLink, I have learned that while the Eclipse API offers a great deal of automation and management, you still have to watch it closely unless you want to spend time ripping your hair out.

Take the example I ran across this morning.

OS: Linux Ubuntu 9.10
Database: MySQL 5.1
API: Eclipse Ganymede
JPA Provider: EclipseLink

This was a simple console app designed to play around with columns while learning the EclipseLink SQL-ish query language. I created a table called "chapters" in my database designed to hold some simple data related to a wargame. (You Warhammer 40,000 fans will like this.) Columns include chapter_name, parent_legion, primarch... obviously all VARCHAR type columns.

One of my columns is called loyalist. It's a BIT column. Hold that in your mind for now...

Now, Eclipse has a nice little feature that allows you to automatically generate entities from your database. Very cool. Run the utility and watch that entity class grow. Nifty.

2 problems:

The first problem is that EclipseLink is going to assume your table name is in ALL CAPS. This is easy to get confused on because the select statement in a case like this reads:

Query query = em.createQuery("Select p from Chapters p");

That syntax is correct because "Chapters" here refers to the entity Chapters, not the table. That means that you're not directly controlling the name of the table the actual SELECT command will be run against. So if your table is named in all lowercase, like mine, running this code will blow up your app.

The solution: Pretty simple, actually. You just have to use an annotation to override the table name. Just add something like this under your @Entity annotation:

@Table(name="chapters")

Good to go. Now EclipseLink will run a SELECT command against table name "chapters" and not "CHAPTERS."

The second problem is a little easier to solve and yet I find it more annoying. When Eclipse generated the entity and tripped across that BIT column, it created a matching member in my class and made it type byte.

KABOOM.

So I manually changed it to boolean in my entity code and now it's happy as a clam.

No comments:

Post a Comment