简体   繁体   English

JPA和DTO,创建DTO的最佳方式?

[英]JPA and DTO's, best way to create DTO's?

We're to use DTO's to send data to and from the presentation layer. 我们将使用DTO向表示层发送数据和从表示层发送数据。

I have a method on a service object called PostAd which posts an advertisement entered by a user. 我在名为PostAd的服务对象上有一个方法,它发布用户输入的广告。 The Ad has an association to another object called AdValues , which contain values for the Ad (title, price, description etc) Ad与另一个名为AdValues对象有关联,其中包含Ad值(标题,价格,说明等)

@Entity
public class Ad {
   @OneToMany
   Set<AdValue> values ...
   ...

I'm wondering what is better as far as the DTO architecture goes: 我想知道DTO架构的优点是什么:

  1. have two DTO's one called AdDTO and the other called AdValuesDTO and call the PostAd method as PostAd(AdDTO, AdValuesDTO) ~or~ 有两个DTO的名为AdDTO ,另一个名为AdValuesDTO ,并将PostAd方法称为PostAd(AdDTO, AdValuesDTO) 〜或〜

  2. Have an AdDTO that contains the AdValuesDTO mimicking the entity structure... this involves having DTO's within DTO's: 有一个AdDTO包含AdValuesDTO模仿实体结构......这涉及内DTO的DTO的:

     AdDTO { Set<AdValuesDTO> adValues ... 

Then the PostAd method is called as PostAd(AdDTO) 然后将PostAd方法称为PostAd(AdDTO)

Or is there another alternative? 或者还有另一种选择吗?

Both would work but with the later approach, you could also use the DTOs to send data from the server to the client. 两者都可以工作,但是使用后一种方法,您还可以使用DTO将数据服务器发送到客户端。 And since having DTOs is already hard and expensive to maintain, you don't really want to multiply them like Jesus with bread. 而且由于DTO已经很难并且维护费用昂贵,所以你真的不想像耶稣那样将它们与面包相乘。

So, to my experience, when you use DTOs, you actually end up having a symmetric structure in parallel of your Entities that you can use in both directions between the client and server. 因此,根据我的经验,当您使用DTO时,实际上您最终会拥有与您的实体并行的对称结构,您可以在客户端和服务器之间双向使用。 And this makes the use of a mapping solution like Dozer possible, or at least easier (and anything that makes using DTOs less painful is welcome). 这使得像Dozer这样的映射解决方案的使用成为可能,或者至少更容易(并且任何使得使用DTO减轻痛苦的东西都是受欢迎的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM