问题
Say I have a domain model where 3 objects interact, Reservation, Vehicle and Fleet. The Fleet has many Vehicles, and each Vehicle can have many Reservations. e.g.
Fleet -1--*- Vehicle -1--*- Reservation
If I want Fleet to have a method getMostPopularVehicle(), I could have it iterate each Vehicle and count the number of Reservations.
If I then want to introduce an ORM for persistence, should I (1) have getMostPopularVehicle() call a data layer method to populate the Fleet, Vehicles and Reservations before iterating it as before? Or should I (2) now just query the database directly to get the most popular vehicle in the data layer method?
My thinking is that (1) is correct, but a database query can be so efficient. Perhaps I am approaching this all wrong?
回答1:
Both approaches are valid. It depends on what you want to achieve; if you can get performance by issueing a (HQL or JPQL or whatever your ORM supports) query, which uses your domain model as well, it is quite legal to do this.
回答2:
If these statistics were expected to be readily available I'd probably go for one of 2 other options that would avoid executing a potentially heavy duty query as often (if at all):
- Retrieve the data by querying the database directly (avoiding the domain model) using CQRS. The returned view models can be cached to avoid subsequent users causing the query to execute again.
- Create a separate reporting database. Key the values on fleet id and vehicle id and maybe increment the value by 5 for every reservation and then decrement EVERY value by 1 once a week, never going any lower than 0. This way, you can keep fairly representative rolling statistics, whilst being able to quickly query the table and find the highest value row for a given fleet.
来源:https://stackoverflow.com/questions/37110145/populate-the-domain-model-from-data-layer-or-query-database-direct