为什么单独的列表必须是实例变量?!为什么不简单地创建一个
getCats方法(和其他方法)并简单地过滤
pets集合呢?试图映射所有内容,恕我直言,事情变得过于复杂。
@Entity@Table(name = "owners")public class Owner extends Person { @oneToMany(cascade = CascadeType.ALL, mappedBy = "owner", fetch=FetchType.EAGER) private Set<Pet> pets; public Set<Pet> getCats() { Set<Pet> cats = new HashSet<Pet>(); for (Pet pet : getPetsInternal()) { if (pet.getType().getName().equals("cat")) { cats.add(pet); } } return cats; }}缺点是每次需要时都会重新创建集合。您可以使用Google Guava之类的工具来简化此操作,并创建一个过滤器列表。
@Entity@Table(name = "owners")public class Owner extends Person { @oneToMany(cascade = CascadeType.ALL, mappedBy = "owner", fetch=FetchType.EAGER) private Set<Pet> pets; public Set<Pet> getCats() { return Sets.filter(getPetsInternal(), new Predicate<Pet>() { public boolean apply(Pet pet) { return pet.getType().getName().equals("cat") } }); }}您还可以在
parsePets方法内部进行操作并使用它进行注释,
@PostLoad以便在所有者从数据库中检索到该方法之后将调用该方法。



