I have to generate a sequential number for groovy-grails app wide use and came up with the following. However, is there a better way to do this?
DOMAIN CLASSES:
class RoastIdCounter {
int counter =0
static constraints = {
}
}
... this one has no views or controller associated with it, it's purely for db interaction in a service class
class RoastId {
Family family
Integer nextId
long timeCreated = new Date().time
static constraints = {
family()
nextId()
}
static belongsTo = [ Family ]
}
class Family extends {
String farmId;
String welcome;
String familyName;
String ourFarm;
String howMuchDoWeGetPaid;
SortedSet pictureAlbums;
SortedSet pictures;
Integer pictureAlbumsCount = 0;
Integer picturesCount = 0;
Date dateCreated = new Date()
Date lastUpdated = new Date()
static hasMany = [ roastIds : RoastId, pictureAlbums : PictureAlbum, pictures : Picture ]
static constraints = {
farmId()
familyName( )
welcome( widget:'textarea' )
ourFarm( widget:'textarea' )
howMuchDoWeGetPaid( widget:'textarea' )
dateCreated()
lastUpdated()
}
String toString() { "$farmId - $familyName" }
} // Family
SERVICE CLASS for dealing with the number generation:
class RoastIdCounterService {
static transactional = true
def getNextRoastId() {
def ric = RoastIdCounter.list()[-1]
if( ric != null ){
ric.lock()
ric.counter = ric.counter + 1
ric.save()
return ric.counter
} else {
return -1
}
}
}
CONTROLLER: ... here I'm just sending the object all pre populated:
def create = {
def roastIdInstance = new RoastId()
roastIdInstance.properties = params
roastIdInstance.nextId = roastIdCounterService.getNextRoastId()
return [roastIdInstance: roastIdInstance]
}
ENV: Grails 1.3.7, PostgreSql 8.4
... so would there be a better way to do this? What potential problems am I overlooking?