In Grails is there something in domain class like onLoad()?

佐手、 提交于 2019-12-24 02:42:11

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7453135/in-grails-is-there-something-in-domain-class-like-onload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!