Thursday, March 11, 2010

GRAILS domain class 'id' field is stubborn- I want a completely different primary key.

http://groovy.dzone.com/tips/initial-value-primary-key
Discusses an issue with setting initial value of id.


static mapping = {
03.id(generator: 'org.hibernate.id.enhanced.SequenceStyleGenerator',
04.params: [sequence_name: 'first_seq', initial_value: 50])
05.}



GOTCHA:

I got it to work, but it's not particularly groovy:

class Branch {
   String id

   static transients = ['name']


   void setName(String name) {
      id = name
   }
   String getName() {
      return id
   }
   static mapping = {
      table 'BK_BRANCH'
      version false
      id generator: 'assigned', column: 'BRANCH_NM'
   }
}

Basically it just allows you to work with the 'name' attribute but it's just a wrapper around the real 'id' attribute.

One gotcha - to save new instances, you need to call save(insert: true) otherwise the insert fails since it seems to see that the id is assigned and assumes it's an update. This is probably due to calling saveOrUpdate() under the hood, which uses null/non-null PK as the flag to determine whether to call save() or update().

- BurtBeckwith

1 comment:

  1. Hi there to all, how is everything, I think every one is getting more from this site, and your views are nice for new users.


    Here is my blog; http://www.drbrucesteinberg.com/

    ReplyDelete