Repository Pattern – How to understand it and how does it work with “complex” entities?

You can read my “repository for dummies” post to understand the simple principle of the repository. I think your problem is that you’re working with DTOs and in that scenario, you don’t really use the repository pattern, you’re using a DAO.

The main difference between a repository and a dao is that a repository returns only objects that are understood by the calling layer. Most of the time the repository is used by the business layer and thus, it returns business objects. A dao returns data which might or might not be a whole business object i.e the data isn’t a valid business concept.

If your business objects are just data structures, it might be a hint you have a modeling problem i.e bad design. A repository makes more sense with ‘rich’ or at least properly encapsulated objects. If you’re just loading/saving data structures probably you don’t need a repository the orm is enough.

If you’re dealing with business objects that are composed from other objects (an aggregate) and that object needs all its parts in order to be consistent (an aggregate root) then the repository pattern is the best solution because it will abstract all persistence details. Your app will just ask for a ‘Product’ and the repository will return it as a whole, regardless of how many tables or queries are required to restore the object.

Based on your code sample, you don’t have ‘real’ business objects. You have data structures used by Hibernate. A business object is designed based on business concepts and use cases. The repository makes it possible for the BL not to care about how that object is persisted. In a way, a repository acts as a ‘converter/mapper’ between the object and the model that will be persisted. Basically the repo ‘reduces’ the objects to the required for persistence data.

A business object is not a ORM entity.It might be from a technical point of view, but from a design pov , one models business stuff the other models persistence stuff. In many cases these are not directly compatible.

The biggest mistake is to design your business object according to storage needs and mindset. And contrary to what many devs believe, an ORM purpose is not to persist business objects. Its purpose is to simulate a ‘oop’ database on top of a rdbms. The ORM mapping is between your db objects and tables, not between app objects (even less when dealing with business objects) and tables.

Leave a Comment

tech