In my limited experience, I\'ve been told repeatedly that you should not pass around entities to the front end or via rest, but instead to use a DTO.
Doesn\'t Spring Dat
We used to use DTOs including the fully traditional layering ( Database, DTO, Repository, Service, Controllers,...) for every entity in our projects. Hopping the DTOs will some day save our life :)
So for a simple City
entity which has id,name,country,state
we did as below:
City
table with id,name,county,....
columnsCityDTO
with id,name,county,....
properties ( exactly same as database)CityRepository
with a findCity(id),....
CityService
with findCity(id) { CityRepository.findCity(id) }
CityController
with findCity(id) { ConvertToJson( CityService.findCity(id)) }
Too many boilerplate codes just to expose a city information to client. As this is a simple entity no business is done at all along these layers, just the objects is passing by.
A change in City
entity was starting from database and changed all layers. (For example adding a location
property, well because at the end the location
property should be exposed to user as json
). Adding a findByNameAndCountryAllIgnoringCase
method needs all layers be changed changed ( Each layer needs to have new method).
Considering Spring Data Rest ( of course with Spring Data
) this is beyond simple!
public interface CityRepository extends CRUDRepository {
City findByNameAndCountryAllIgnoringCase(String name, String country);
}
The city
entity is exposed to client with minimum code and still you have control on how the city is exposed. Validation
, Security
, Object Mapping
... is all there. So you can tweak every thing.
For example, if I want to keep client unaware on city
entity property name change (layer separation), well I can use custom Object mapper mentioned https://docs.spring.io/spring-data/rest/docs/3.0.2.RELEASE/reference/html/#customizing-sdr.custom-jackson-deserialization
To summarize
We use the Spring Data Rest as much as possible, in complicated use cases we still can go for traditional layering and let the Service
and Controller
do some business.