Guys,
I have a following domain class:
class Product {
String name,
String productRecord,
static transients = ['productRecord']
}
productRecord is a field which is generated automatically based on the id of the Product instance.
开发者_开发知识库So I've been thinking, is there a place which will be automatically called when a domain instance is load to generate the productRecord number?
What's the best way to do that?
You can probably leverage the built-in Domain Events:
GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events:
- beforeInsert - Executed before an object is initially persisted to the database
- beforeUpdate - Executed before an object is updated
- beforeDelete - Executed before an object is deleted
- beforeValidate - Executed before an object is validated
- afterInsert - Executed after an object is persisted to the database
- afterUpdate - Executed after an object has been updated
- afterDelete - Executed after an object has been deleted
- onLoad - Executed when an object is loaded from the database
Have a look at the docs for some examples.
Typically this is done by creating a read-only getter method and put the generation logic in there. For example:
class Product {
String name,
String getProductRecord{ "Record " + id },
static transients = ['productRecord']
}
Another example is available here.
精彩评论