Tuesday, 11 May 2010

Random Grails tip: Using a DB reserved word as a domain class name in Grails

We recently came across a situation where we couldn't our Grails app was failing because it was trying to create a table with the name of 'Condition', which turns out to be a reserved word in MySQL... We worked around it by changing the name of the table to 'conditions' by using the Grails ORM DSL, but it turns out there is another way.

Backtick to the rescue...
Hibernate allows you to use backticks (`) to indicate that a name should be escaped - you can simply use this in your grails mapping. For example, we could have used:

class Condition {
String property1
String property2

static mapping = {
table '`condition`'

To be honest, I'm not sure why Grails and/or hibernate don't escape all table and column names by default (I'm sure there is a good reason) - there is an open JIRA issue in Grails around this very problem...