02
Sep 09

GORM custom id mapping

I’m not sure why this is so undocumented. There is documentation about all these options, but you must collect them all from different sections. So I figured I’ll document it here for the sake of people finding it, before they post it to the grails users list for the thousandth time never really getting a straightforward response it seems.

GORM defaults to using ‘id’ field as the primary key, so it injects it if you don’t explicitly define it. You can easily change its type from Long to say String, but some Hibernate baggage follows. Basically, anything outside of the default Long id will not work, unless you also map is as an ‘assigned’ id, though hibernate will not try to automatically assign a long id during persistence of a new object. There are also cases that besides the type changes, you want to have the field name something else. I mean, when you have a User class, you might want to refer to its primary key as username and not just a plain generic id.

Here is how you completely remap the primary field (non-composite).

class User {
  String username;
  String password;

  static constraints = {
  }

  static mapping = {
    table 'users'
    id generator: 'assigned', name: "username", type: 'string'
  }
}

This will allow you to use username as the primary key field on this domain class, as opposed to id. id field no longer exists and is completely replaces by a string field username. The proper database schema is also created with username column as the primary key.

3 comments

  1. Thanks Man, Very True!! Good That You Documented This. Very Helpful!!

  2. You’re my hero … seriously … I’ve looked for this for months.

Leave a comment