سؤال

I have two domain entities: Employee and Team. As you can guess Team has 0...* Employees. what is the correct of modeling them?

option 1:

class Team{
  List<Employee> members;
}

this maybe the most intuitive way, but this means when I only need to display Team infos, I have to load a lot of Employees which is a totally waste. maybe I can add some lazy load(maybe throw proxy) mechanism but this will bring us a lot of complexity

option 2:

class Team{
  List<Long> memberIds;
}

this option won't load too many unnecessary Employees but maybe (I'm not sure) not a good design from the view of modeling

option 3:

class Team{} 
class Employee{
  Team team;
}

in this option I can query a Team's Employees by a Employee's property. But I think maybe (I'm not sure) from the view of modeling, a Employee shouldn't have knowledge of how it be organized, and also Employee is an entity which can live without a Team

what do you think guys?

هل كانت مفيدة؟

المحلول

First option is simple & best.

class Team{
    List<Employee> members;
}

You can set a batch-size in Hibernate, or many other JPA implementations, so that when the Employees do have to be fetched they are fetched 10 at a time or somesuch. This takes little time to fetch, and Hibernate won't fetch a collection until you require it.

The "set of IDs" doesn't help -- it doesn't provide names of team-members, and it doesn't make loading any faster when you do need them.

The general rule is, don't optimize until you need to.

But there are two alternatives you can consider, if you need to:

  1. Turn on EH-Cache or similar second-level cache for Team.members and Employee;
  2. Store an aggregate "team member names" property in Team. Notes: This would have only limited guarantees of up-to-dateness, and has to be to truncated to avoid overflowing it's maximum column-size.

But as an 'indicative display text', rather than an authoritative value, the second option would be fine.

نصائح أخرى

You must consider the fact that you should not have members in your team that are logically equal to each other (or maybe you want 1000 'Agent Smith' clones fighting for your team :-) ). Better to model the relationship like this:

Set<Employee> members;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top