C++ – How to Encapsulate Database Access

cdatabase

What are some examples of good class structures used to manage database access? I am a fan of class encapsulation and would prefer the containers (e.g. car) not to perform database tasks.

I would also like the ability to easily drop in things like a database cache in future.

I often take the pattern of container classes, complete with getters and setters for validation and database access performed by a single singleton class. That being said, this often gets mixed between the two and becomes quite confusing.

Sorry if my question is hard to understand; I'm not absolutely sure on terms regarding databases. Please feel free to ask for clarification if needed.

Best Answer

I prefer the Repository Pattern to encapsulate data access. In a nutshell, the repository is responsible for loading all the data required for a specific object. Say you have a Car object, like in your example. But all the attributes for the car, make, model, year, owners, features (CD player, 4wd etc) are stored in various tables throughout the database. The repository determines how to load and save the data. If multiple smaller queries are needed, fine, but only the repository pattern needs to know that. The service layer invoking the repository only needs to know which repository to invoke.

That can then be combined with the unit of work pattern. So in your example, the service layer would say it needs to load a car entity, it has some sort of unique identifier, and sends that identifier down to the repository. The repository returns the car entity. Some other code manipulates the car entity and sends that entity back to the repository so it can be saved.

If you really want to go all out, the repository layer would only expose interfaces, such as ICarRepository. The repository would contain a factory which the service layer would use to get the ICarRepository interface. All database access would be hidden behind an interface, which makes unit testing much much easier.