Use custom method for id generation in grails

07 / Jun / 2010 by Uday Pratap Singh 0 comments

Hibernate usage in Grails is one of my favorite topic so to learn more about it I just started reading Hibernate. In hibernate I found that user can manually assign the id of object but in grails we need to rely on it and it generates it own sequential ids. Though there is no harm and saves our time as well to generate id, but there may be the case where we need to assign the id of an object manually.

As the grails uses hibernate, the same behavior is available in grails as well. There are different methods to generate id for object by default Grails uses ‘native’ method which rely on the id generation capability of database (which is sequential most of the time). So to change this behavior and use the custom id generation we just need to do the changes in static mapping.

static mapping={
        id generator:'assigned'

and now in controller you can write something like

or to make you controllers clean you can do that in beforeInsert

def beforeInsert = {

I hope this will be helpful for some people.

Hope it helps
Uday Pratap Singh


Leave a Reply

Your email address will not be published. Required fields are marked *