views:

108

answers:

2

I'm building a set of CRUD screens for a Repository. The member objects are large enough that I'd rather not load lots of them into memory all at once - as when generating search results.

Since all I need for search results are a couple of properties - e.g., "name" and "id" - I could just query the underlying database - but I don't want to bypass the repository, since that would negate a lot of its value.

The Repository Pattern intros and tutorials I've found don't cover this scenario. They focus on saving/retrieving/deleting one fully-populated object at a time.

I am familiar with the Proxy pattern for lazy-loading objects. But is that how the big boys do it? Is there a well-established solution to this problem?

A: 

You define queries on the repository interface which pull back the data you are after.

I think the big boys use an ORM layer (like Hibernate) however, and pass a defined query to the ORM.

mcintyre321
So if a query specifies that I'm only interested in names and IDs, my repository can return a set of objects with most of their properties set to NULL?
Metaphile
the accepted answer seems good to me.
mcintyre321
+1  A: 

If you go strictly by DDD, I think your searches should return fully populated objects. But sometimes you have to bend the rules.

I can tell you what not to do:

  1. Do not retrieve only the data you need and still return not-fully-populated instances of the entity class. This can easily turn into disaster. You end up with different query methods that seemingly return fully populated entities - but in reality it will depend on which query method that was called. Expect confusion.

  2. Do not roll your own lazy initialization scheme. It is difficult and error-prone. I have done this once, and I can safely say it was not worth the effort.

So, what remains? My vote is to grab the data you need, and create a class that has only the fields you are planning to populate, and return a list of those. Now, anyone calling your search function knows exactly what they are getting: a subset of the actual data. When you need the full entity, you will have to hit the database again.

Here is an example of what I mean in Java:

public class CakeRepository {
    public List<CakeProjection> getCakesByManufacturer(String manufacturer);

    public Cake getCake(long id);

    ...
}

public class CakeProjection {
    private long id;
    private String cakeName;

    ...
}
waxwing
Yes, yes, yes, it all makes sense. Thank you very much. Now I just need to come up with a name for these partial entities. "Projection", huh...?
Metaphile