Over a million developers have joined DZone.

Initial value of primary key in Grails

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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?

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}