Igor
Igor

Reputation: 34011

Persist column order from Grails domain to database

When Grails creates a table from a domain object, is it possible to specify the column order? I'd like it to preserve the column order as specified in the domain. Instead, it seems to be mostly alphabetical. I could not find anything in the documentation. I've found this article that details specifying constraints, but that did not appear to fix the issue for database columns.

Example:

class Foo {
    Long id
    String zee
    Integer baz
    Integer bar
}

I'd like the database columns to then be ordered as:

id | zee | baz | bar

Instead I get something closer to:

id | bar | baz | zee

Upvotes: 5

Views: 1607

Answers (2)

trd3v3lop
trd3v3lop

Reputation: 343

This is the only way to do it as I know. Use static constraints and write them with your order

class Foo {
    Long id
    String zee
    Integer baz
    Integer bar
}

static constraints = {
    id()
    zee()
    baz()
    bar()
}

Upvotes: 2

cdeszaq
cdeszaq

Reputation: 31300

You can always create the DB outside of Grails and put the columns in whatever order you wish and Grails will happily use the schema you provide (assuming only the column ordering is different from what it wants to create by default)

An even better option, as @Burt pointed out, is to use the database migration plugin to create (and manage) the database. It lets you have fine-grained control over the database in a database-agnostic way and also has the massive advantage of making your DB schema and schema changes versioned along with your code, for both upgrades and rollbacks.

Upvotes: 2

Related Questions