0

An entity may contain some properties like id etc that I think no need to show in Frontend, so I turn to DTO that only holds the property I think useful. For example, the Article and ArticleDTO, here is the code.

Article.class

@Entity
public class Article implements Serializable {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String subtitle1;
    private String subtitle2;

    ...

    private List<Block> blocks;

}

ArticleDTO.class

public class ArticleDTO implements Serializable {

    private Long[] categoryIds;
    private String[] keywords;
    private String title;
    private String subtitle1;
    private String subtitle2;

    ...

    private List<BlockDTO> blockDTOs;

}

And my question is that can I own these two properties (categoryIds and keywords) in my DTO? Because I think my Frontend will return the JSON like this:

{
  "categoryIds": [
      1,
      2
  ],
  "keywords": [
      "amazing",
      "incredible",
      "easy"
  ],
  "title": "Shock! A student from ZJNU.....",
  "subtitle1": "subTitle1",
  "subtitle2": "subTitle2",

  ...

}

If I shouldn't do this, what's the right approach? And if I can do this, could you please also tell me what's the best way to mapper my ArticleDTO to Article? Thank you so much!

MarcuX
  • 331
  • 4
  • 16
  • 1
    A DTO is a Data Transfer Object. Its purpose is to transfer data. So you model it by thinking about the data you want to transfer. Entities are irrelevant. – JB Nizet May 11 '17 at 06:29
  • It sounds like you're wanting to convert JSON to a DTO. Java has a built in library for this called Jackson. This question will help: http://stackoverflow.com/questions/10308452/how-to-convert-the-following-json-string-to-java-object – Wheeler May 11 '17 at 06:51

0 Answers0