views:

326

answers:

2

I use GORM to generate my database's DDL from groovy classes. Which is great. However, the order of fields in the generated SQL is not the same as the order of fields in the class. For example, if I create the class

class Person
{
  String firstName
  String lastName
  String address
  String email
}

the following SQL is generated (for MySQL)

CREATE TABLE `test` (
  `id` bigint(20) NOT NULL auto_increment,
  `version` bigint(20) NOT NULL,
  `address` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The fields have been sorted into alphabetical order (after the autogenerated id and version fields). This is O.K. in this instance, but I have some much wider tables in which there is important contextual information in the order of the fields.

Here is my question: How do you tell GORM to order the fields in SQL in the order of declaration in the groovy class?

+1  A: 

I'm not absolutely sure about this, but the constraints closure defines the order of the fields in the views, maybe that reflects to the fields on tables.

class Person
{
  String firstName
  String lastName
  String address
  String email
}

static constraints = {
  firstName()
  lastName()
  address()
  email()
}
elbicho
Thanks for the suggestion! I just tested this and unfortunately it does not appear to change the order of generated fields in the DDL.
mycro.be
+1  A: 

There doesn't appear to be a way to specify the ordering, but you could always create your own tables as you want them and provide name mappings in your domain classes. You could also let GORM create the tables, and then recreate the tables in the right order, and turn off the automatic DDL stuff in GORM after that. If you use the field and table names that GORM chose, you'll not need to add any mappings.

John Flinchbaugh
Thanks John. This is the approach I am currently taking. It's a shame that there isn't a groovier way to do it.
mycro.be