开发者

Is a variable declaration in grails the same as a belongsTo relationship?

I am trying to set up a few domain classes. I will explain it in english, and I am wondering how the domain would be set up in grails. Capitalized words are my domains

An Employee has an Education. An Employee has many Employer (past and present). An Employee had one or many Project for each Employer. Project have a Role, Client...etc

Now my question is, when for example, I define Employer, will I put

 hasMany = [projects:Project]

and ALSO in Project put

 belongsTo = [employer:Employer, employee:Employee, client:Client]

Mind you - many employees may have worked on the same project, so I might want to figure out a way to define that?

Would I开发者_StackOverflow中文版 also put in Employer:

  ArrayList<Project> project = new ArrayList();
  static hasMany = [projects:Project]

Or is that redundant?


Variable declaration is not the same as defining a belongsTo relationship. belongsTo mostly comes into play with cascading of persistence actions, notably deletes. For example, if you have two classes:

// Employee.groovy
Project project

// Project.groovy
static belongsTo = Employee

If a specific Project belongs to an Employee, and that Employee is deleted, the Project will also be deleted. Here's another SO question with a good answer.

For your second question, yes, defining the List is redundant. If you do:

static hasMany = [projects: Project]

The Collection is implicitly defined for the domain. However, there are certain cases where you may need to initialize the Collection for use within constraints. See this issue for more details.


It is redundant but your example isn't entirely accurate to what you are describing. By default, when you define a hasMany, Grails will create a Set. What your code will do is use an ArrayList instead of a Set but the relationship is exactly the same. I assume you meant for your project ArrayList to actuually be plural (projects).

Also, just a side note, you should always use the Interface to declar your typed variables rather than an implementation:

List<Project> projects = new ArrayList<Project>()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜