Saturday, April 28, 2012

Keyword column names with Hibernate

I ran in to an interesting problem today, and I thought I might as well help pass it around. I was attempting to create a new Hibernate class for a new table I had created. One of the column names for this table was "index" - which, unfortunately, is a keyword in MySQL. So the Hibernate code I wrote looked something like this:

    @Column(name="index")
    public int getIndex() {
        return index;
    }

When I attempted to run my new code, I was getting a very uninformative error attempting to write to that table:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index, blahblahotherstufffrommyquery... ' at line 2

Excellent. Perfectly clear. Yeah.

After turning on show sql and going over to MySQLWorkbench, I found that I was getting an error there too - as it turns out, the column "index" needed to be escaped with back ticks, "`index`". Why Hibernate does not do this by default, I don't know. Luckily, as it turns out, it is a fairly easy fix - just add the back ticks to the column name in the annotation, like such:

    @Column(name="`index`")
    public int getIndex() {
        return index;
    }

This makes things work much easier. Just something to bear in mind for future reference.

No comments:

Post a Comment