February 15, 2011 | Category: Uncategorized

Jdbc and Enums

After months of using JPA/Hibernate almost exclusively, I got caught out on a relatively simple bug when using JDBC more directly (well, via Spring’s JdbcTemplate):

public List<SomeObject> fetchSomeObjects(RecordType recordType) {
  Map<String,Object> params = ...//Map creation;
  params.put("recordType", recordType);
  return namedParameterJdbcTemplate.query("select * from someObject where recordType =  :recordType",

That was from memory, so it may be a little off, but it should give you the basics of what the code was doing. It looks okay to my eyes, but, of course, it wasn’t. When run an exception was being thrown from the bowels of the JDBC code saying that RecordType couldn’t be converted to a JAVA_OBJECT.

Odd, I thought. It had worked perfectly well with an in-memory database (HSQL) but now wasn’t working when deployed on a hosted database (SQL server).

I couldn’t spot it straight away, so a quick debugging session revealed the problem: JDBC doesn’t play nicely with enums. RecordType, an enum, was being passed to JDBC verbatim without any attempt for it to match up with the recordType column (a varchar column); and that just doesn’t work. You need to explicitly convert from an enum to a String.

Thankfully, it was a one-line fix:

params.put("recordType", recordType.toString());

It doesn’t read quite as neatly but it works. The fact that the original version reads quite well (the value for “recordType” is called recordType) actually makes the bug harder to spot. Now, back to JPA.