Is it problematic that Spring Data REST exposes entities via REST resources without using DTOs?

前端 未结 3 1851
说谎
说谎 2021-01-30 02:47

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

3条回答
  •  迷失自我
    2021-01-30 03:14

    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:

    1. City table with id,name,county,.... columns
    2. CityDTO with id,name,county,.... properties ( exactly same as database)
    3. CityRepository with a findCity(id),....
    4. CityService with findCity(id) { CityRepository.findCity(id) }
    5. 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.

提交回复
热议问题