与DTO关联实体的实体

时间:2017-05-18 19:20:22

标签: java hibernate persistence

我想问一下将实体与关联实体转换为DTO的良好做法。

所以,例如我有3个enities:

@Entity
@Table
public class First {
    @Id
    private int id;

    @OneToMany(mappedBy = "first")
    ...
    private List<Second> second;

    @ManyToOne
    ...
    private Third third;


@Entity
@Table
public class Second {
    @Id
    private int id;

    @ManyToOne
    ...
    private First first;

    @OneToMany(mappedBy = "second")
    ...
    private List<Third> third;



@Entity
@Table
public class Third {
    @Id
    private int id;

    @ManyToOne
    ...
    private Second second;

    @OneToMany(mappedBy = "third")
    ...
    private List<First> first;

将所有这些转换为DTO的最佳做法是什么? 我不想使用外部库。

就像你看到的问题是它的重复使用和嵌套的协议。

问候。

编辑: 有人可以给我一些用于映射他自己使用的DTO的库名吗?

1 个答案:

答案 0 :(得分:2)

这可能会有所帮助:

我建议使用自定义dto来避免循环(导致StackOverFlowError)。管理您正在传输的内容的优势。使用上面的实体类,我构建了下面的dto。

我对像lombok一样依赖 &#34; org.projectlombok&#34; %&#34; lombok&#34; %lombokVersion

在我的构建中。

构建我的自定义DTO

@Data
public class FirstDTO implements Jsonable {
   protected String id; 
   protected ThirdDTO third;

   public FirstDTO(){}

   @JsonCreator
   public FirstDTO(@JsonProperty("id") String id,
                     @JsonProperty("third") Third third){
          this.id = id;
          this.third = third;
     }
}
相关问题