Most suitable way to transport entities from service to front end in Spring boot

时间:2019-05-01 08:41:09

标签: java spring spring-boot mapstruct

I have currently found out three possible ways to send objects (entities) from service to the front end.

  1. JSON views

  2. DTO using MapStruct for example.

  3. DTO without MapStruct (as per first comment)

I guess that using JSON view may cause issues with lazy loading inside the entities since any entities having this will be outside of the hibernate session (assuming that we are working with @Transactional in our services which is most common).

I also don't prefer the third option because in that case, I need also to implement the mappers myself.

I finally chose to work with MapStruct. Is that the best way?

1 个答案:

答案 0 :(得分:1)

我认为没有最合适的方法将实体从服务传输到前端。这应该由开发团队决定,什么是最适合他们的。但是,我个人希望将实体与REST DTO分离,这样可以自动排除使用JSON视图的第一种选择。

使用MapStruct的其他两个DTO选项和不使用MapStruct的DTO(手动代码)相同。 MapStruct生成的代码是一个简单易读的代码,与人类编写的代码完全相同。您可以自定义世代,还可以添加自定义映射(然后MapStruct将退出)。