should i use jpa entity in rest request and/or res

2020-03-12 05:28发布

问题:

I have a situation in which i can send JPA entity as rest request and/or get JPA entity as rest response

@RequestMapping(value = "/products", method = RequestMethod.POST)
public @ResponseBody ProductDetailsResponse createNewProduct(@RequestBody ProductDetails newProduct)
        throws Exception {

ProductDetails is an entity

@Entity
@Table(name = "product")
public class ProductDetails {

Should I use this, or have some kind of transformation from entities to another kind of objects

回答1:

There is no hard and fast rule but its not considered a good practice ( for very good reasons & Its very opinionated view ) to use JPA entities as DTOs ( Data Transfer Objects ).

Other than DTOs being lightweight versions of entities in terms of size, there are other advantages too.

One such advantage that I realized is lighter versions of relationships too e.g. for a One - To - Many unidirectional relationship , your child entity will reference back your parent entity too but you can break that chain in DTOs so avoid lots of JSON conversion and infinite looping related issues.

I find doing JSON to Object conversions ( and vice versa ) at DTO level a bit easier than at entity level because entities represent DB diagram not client business diagram.

One simple generic utility class to do conversions ( from DTO to Entity and vice - versa ) will be enough. You can use model mapper API as described here .

I don't let entities cross service layer boundary, its all DTOs at controller and I do conversions at controller.

There are very interesting questions on SO on this topic that you can browse ,

Should I convert an entity to a DTO inside a Repository object and return it to the service layer?

Conversion of DTO to entity and vice-versa

REST API - DTOs or not?

Additional boiler plate code is one disadvantage of DTO approach.



回答2:

From technical point of view, it is fine to use entity in response. Entity must just be serializable to response output format (JSON or XML).

It is good idea to write test that will create complete entity object (all fields set to non null) and try to serialize it. Even single non-serializable field will cause exception. You rather want to discover that during testing than after release.

In simple cases (CRUD applications), where every field of entity is needed in response this is fine option.

If you do not need every field of entity in response, you may use @JsonView.

If your response is significantly diffrent than entity (new fields, transformations) it is better idea to create separate DTO object for response. That way, you will be able to evolve web API (DTO) and datatabase schema (entity) separately.