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

Melad Basilius :

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

Sabir Khan :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=438940&siteId=1