Populate the domain model from data layer, or query database direct?

别来无恙 提交于 2019-12-22 10:12:10

问题


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):

  1. 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.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!