AutoIncrement fields other than id in grails

I am new to Grails. I have a field in my domain object that I define as String .

 String ponum 

When I click the first time on the creation page, the ponum field should display 0001, and then it should be stored in the database. And when I click a second time, the "ponum" field should display 0002, and then it has to save to the database. Every time I click on the page creation, the "ponum" field should auto-increment and save its database.I google, but I did not receive any document. thanks

+6
source share
2 answers

Anyway, they still get the identifier (assuming you are using regular rdbms with the standard genaerator identifier), why not just pretend to have the ponum variable based on id there?

Just add getter to the domain class:

 class Page { String getPonum() { String.format( "%04d", id ) } } 
+6
source

According to this answer , it is not possible to use sleep mode generators (those used for identifiers). If you really need to use Hibernate generators, the workaround is described in the answer too.

In your case, you can use an interceptor to generate 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' } } 
+1
source

Source: https://habr.com/ru/post/900995/


All Articles