Business Layer Objects vs DTO with Logic in MVC

design-patternsmvcspring-mvc

Let's say I have a Spring MVC project, in which I'm using DTO to get data from a database and to pass data to the UI. Let's suppose that I have a UserDTO and in my business layer I have to do something with that, but I need to put logic in the User and the DTO pattern says that no logic is allowed (or just simple logic).

Should I transform this UserDTO to a User object in order to have the logic and then make a UserDTO to give it to the UI? Or just use the UserDTO and process it in the business layer?

Thanks

Best Answer

Your data layer should be giving you domain objects, not data transfer objects.

The database query would return User class instances which class houses the domain logic. Your business service that is calling the data layer should be where you do whatever steps that are needed for your use case, such as calling multiple data access objects and obtaining all necessary domain information, invoking all appropriate business functions and finally mapping that data into your data transfer object for the UI rendering process.

There are use cases where your data layer may return value objects that may not necessarily be entities as they are stored in the datastore. For example, if you have a table with a large number of columns but you are only interested in a small subset of the columns or a specific view across several entities, you may have your ORM return you a list of instantiated objects that aren't managed entities. These value objects are often immutable but aren't necessarily required to be.