7

I'm new to Grails. I have a field in my domain object which I define as an String.

String ponum

When i click first time on create page ,the "ponum" field has to display 0001 and later it has to save in database.And When i click on second time the "ponum" field has to display 0002 and later it has to save in database.Everytime i click on create page "ponum" field has to autoincrement and save it database.I google ,but i did not get any document. thanks

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Sathish Kumar
  • 97
  • 1
  • 5
  • 1
    The version field (which is automatically added by grails) also tells you how many times the row has been updated. Grails automatically increments it each time the row is updated, so if that's all you're looking for, it might work for you. – Todd Nov 08 '11 at 10:27

2 Answers2

6

As things get an id anyway (assuming your using a regular rdbms with standard id genaerator), why not just pretend there's a variable ponum which is based on the id?

Just add a getter to your domain class:

class Page {
  String getPonum() {
    String.format( "%04d", id )
  }
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Thanks for reply its working for me.But When i click on create page it is showing "null".Instead of i need to show new ponum in create page. – Sathish Kumar Nov 08 '11 at 10:02
  • @SathishKumar Ahhh... the id isn't created until it is first saved... You could change it to: `id ? String.format( "%04d", id ) : 'Not saved'` to show something to the user before it is saved, or use something like a `sequence` if your (database supports them). However this would mean that clicking `create page` would create lots of new `ponum`s which might never make it into the database – tim_yates Nov 08 '11 at 10:07
1

According to this answer, it is not possible to use hibernate generators (those used for ids) to do that. If you really need to use Hibernate generators, a workaround is described in the answer as well.

In your case, you could use an interceptor to generator your ponum property when inserting a new object:

class Yours {
  int ponum

  def beforeInsert() {
    def lastPonum = Book.list([sort: 'ponum', order:'desc', max: 1])
    if(lastPonum)
      ponum = (lastPonum.pop().ponum as int) + 1 as String
    else
      ponum = '0'
  }
}
Community
  • 1
  • 1
Antoine
  • 5,158
  • 1
  • 24
  • 37
  • 4
    This answer is not thread-safe. If you have two threads doing an insert concurrently, they will both get the same ponum. – mmigdol Aug 05 '15 at 22:52