The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Michael (1) [Avatar] Offline
Hi Chris. I was reading over your examples and was wondering how you deal with navigating associations from your entity or do you always use the repository for querying?

Father with children

public class Father {
private List children = new ArrayList();

//Hibernate managed
public List children() {
return children();

//List children over a certain age
public List children(int age) {
could call children() and exclude
but what other way would you do this?



FatherRepository rep = new FatherRepositoryImpl(..);
Father father = rep.load("dad");
List dependentsOverAgeOf5 = father.children(5);

In the case above I would like to query for the children over the age of 5 but keep that knowledge inside the domain object.
ceracm (113) [Avatar] Offline
Re: How to navigate associations from your entity?

Thanks for your question and sorry for the late response.

It typically makes sense for the parent object to be responsible for querying the children collection as you described.

This could be done in a couple of ways:

1. In Java: Father.children() could simply iterate through the children collection testing each child. This is simple, easily testable and works well for most families smilie

2. In the database: if there are a large number of children, you probably want to avoid instantiating the entire collection if the filter will only return a few of them. In this case, it makes sense for the parent object to delegate to a repository to execute the query/Hibernate collection filter.

Of course, option #2 then gets into the issue of how the parent entity obtains a reference to the repository that is discussed in chapter 4. Typically, it has to be passed as a method parameter:
List children(int age, ChildRepository r)

Alternatively, you can use a dependency injection mechanism such as that provided by Spring 2.0. to inject the repository into the Father object.

If you don't like either of these ways of accessing the repository from an entity you make the repository solely responsible for implementing this and not involve the Father.

interface ChildRepository {
List findChildrenForParent(Father father, int age);

However, it is nicer for the Father object to hide this repository from its clients.

I hope this helps and look forward to hearing your thoughts.