简体   繁体   中英

Grails: how to “access” a domain class instance variables across other domains?

Sorry, I could not come up with a better title for this question, but gave my best shot. I have domain classes User and Post -- a user has many posts , and a post belongs to a user, as follows.

class User {

    String name

    static hasMany = [ posts : Post ]

    static constraints = {  }
}

class Post {

    String content

    static belongsTo = [ user : User ]

    static constraints = {  }
}

I have another domain class Status as follows.

class Status {
    Boolean isActive

    static constraints = {
    }
}

Each user and post has a status , and I am wondering how to implement that? Couple of different approaches I can think of doing this are:

  1. Inheritance: Let User and Post extend Status , and use static mapping = { tablePerHierarchy false } in the Status . Then User and Post automatically inherit the instance variables of Status (and they get persisted in separate tables). However this approach does not seem appropriate as User and Post are not actually a Status .
  2. I can redefine the Status instance variables in User and Post , and then do something like this in User and Post
static constraints = {
        importFrom Status

        // other constraints 
    }

  • Is one approach better than the other?
  • Is there a better way of achieving this?
  • Is there a best practices that Grails pros can recommend?

Note: The Status domain has many instance variables (what is presented here is a stripped down version), and I need to "access" its instance variables from many other domains ( User , Post , and many other). Otherwise I could have just gotten ride of the Status domain and just define those instance variables in User and Post separately. The approach 2 mentioned above kind of does this, except that it saves re-typing the constraints by just using importFrom Status .

I agree that Inheritance is not a clean option. Your second approach seems right but why do you need the "importFrom"? By defining Status as an instance variable in User and Post, Status will take care of the validation of its own variables. You can still access Status' instance variables from Post/User as like this:

user.status.isActive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM