Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoIncrement fields other than Id in grails

Tags:

grails

groovy

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

like image 305
Sathish Kumar Avatar asked Nov 08 '11 04:11

Sathish Kumar


Video Answer


2 Answers

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 )
  }
}
like image 167
tim_yates Avatar answered Oct 18 '22 08:10

tim_yates


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'
  }
}
like image 23
Antoine Avatar answered Oct 18 '22 10:10

Antoine