我应该在休息请求和/或响应中使用jpa实体吗? [英] should i use jpa entity in rest request and/or response

查看:77
本文介绍了我应该在休息请求和/或响应中使用jpa实体吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我可以将JPA实体作为休息请求发送和/或获得JPA实体作为休息响应

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

ProductDetails 是一个实体



<$ p $ @Entity
@Table(name =product)
public class ProductDetails {

我应该使用它,还是从实体到另一种对象进行某种形式的转换

解决方案

没有硬性规定,但它不被认为是使用JPA实体作为DTO(数据传输对象)的良好惯例(出于非常好的理由及其非常有见地的观点)。

除了在大小方面是实体的轻量版本,DTO还有其他的优点。


我认识到的一个优点是关系也更轻。对于一对多的单向关系,您的子实体也会引用您的父实体,但是您可以在DTO中打破该链,这样可以避免大量JSON转换和无限循环相关问题。

我发现在DTO级别执行JSON to Object转换(反之亦然)比在实体级别更简单,因为实体表示DB图表而非客户端业务图表。

一个简单的通用工具类可以完成转换(从DTO到实体,反之亦然)就足够了。您可以使用此处所述的模型映射器API



我不让实体跨越服务层边界,它的所有DTO都在控制器上,我在控制器上进行转换。



有关这个主题的SO非常有趣的问题,您可以浏览,

我应该转换一个实体到存储库对象中的DTO并将其返回到服务层?



将DTO转换为实体,反之亦然

REST API - DTOs或不??



<其他锅炉板代码是DTO方法的一个缺点。


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

解决方案

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.

这篇关于我应该在休息请求和/或响应中使用jpa实体吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆