In a domain class, I’m using the “assigned” ID Generator:
static mapping = {
id(generator: 'assigned')
}
Before an entity is saved, I’d like to make sure that it has an id set.
def beforeSave() {
if (!id) {
id = DomainUtil.newId();
}
}
Unfortunately, this does not work:
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): was.Product
The “beforeSave” hook seems to be invoked after the check for the id takes place. Is there a way to work around this? Im using Grails 2.1.1.
EDIT:
This seems to work, but it is quite hacky: On the propert declaration, I added:
String id = DomainUtil.newId();
This initializes the id with a “default”, which can then be modified before calling save().
You can try
beforeValidate. It is probably the closest thing to what you are looking for. I’m not sure it will work in your specific case though. It will get executed on an insert or update becausesave()callsvalidate().