Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Marcin Świerczyński is a software developer especially interested in Java and Python languages, Java-based technologies and mobile applications development. He strongly believes in Software Craftsmanship as a way to build reliable and maintainable software. Marcin has posted 3 posts at DZone. View Full User Profile

Initial value of primary key in Grails

03.02.2010
Email
Views: 4100
  • submit to reddit

I’ve recently came across a small issue in my Grails application. I had to set an initial value of auto-generated identifiers of my objects. Moreover, I had to use two different values in two classes. For example, identifiers in one table in database should start from 50, while in another table – from 1000. How to get this in Grails domain classes?

You have to use SequenceStyleGenerator with its parameter – initial_value. You can do this with generator phrase in mapping clousure:

class FirstClass {
static mapping = {
id(generator: 'org.hibernate.id.enhanced.SequenceStyleGenerator',
params: [initial_value: 50])
}
...
}

class SecondClass {
static mapping = {
id(generator: 'org.hibernate.id.enhanced.SequenceStyleGenerator',
params: [initial_value: 1000])
}
...
}

Unfortunately, in this case you’ll finish with the same sequence generator in both classes. That means that you’ll get one sequence shared between two tables. How to avoid this? Just specify sequence name using next parameter – sequence_name:

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

class SecondClass {
static mapping = {
id(generator: 'org.hibernate.id.enhanced.SequenceStyleGenerator',
params: [sequence_name: 'second_seq', initial_value: 1000])
}
...
}

What do you think about my solution? Do you know another one?

5
Your rating: None Average: 5 (1 vote)
Published at DZone with permission of its author, Marcin Świerczyński.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)