【问题标题】:How to map bidirectional Entities to DTO in Java如何在 Java 中将双向实体映射到 DTO
【发布时间】:2016-09-26 12:07:01
【问题描述】:

有人可以帮我解决这个问题吗?我尝试使用 mapstruct,它工作得很好,但仅适用于没有双向关系的实体。

例如我有实体:

@Entity
public class Pacients implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int pacientId;

    // bi-directional many-to-one association to Doctori
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "doctorId")
    private Doctors doctor;

    //setters and getters
}

@Entity
public class Doctors implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int doctorId;

    // bi-directional many-to-one association to Pacienti
    @OneToMany(mappedBy = "doctor")
    private List<Pacients> pacients;

    //setters and getters
}

DTO:

public class PacientsDto implements Serializable {


    private int pacientId;
    private Doctors doctor;

    //setters and getters
}


public class DoctorsDto implements Serializable {

    private int doctorId;

    private List<Pacients> pacients;

    //setters and getters
}

当我尝试将它们映射到 dto 时,由于这种双向关系,我得到了 StackOverflowError。

知道如何解决这个问题吗?我也会接受不使用 mapstruct 的解决方案。

如果需要任何详细信息,请告诉我。 谢谢!

【问题讨论】:

  • Java 和实体框架在同一个问题中。你确定吗?
  • 你是对的。我将专注于如何提出问题,以便尽可能清晰。谢谢!
  • 我假设您的 Dtos 应该相互引用,即 PacientsDto 不应该引用 Doctors 而是引用 DoctorsDtoDoctorsDto 相同。

标签: java jpa mapstruct


【解决方案1】:

您将有两种映射方法,一种用于映射医生,另一种用于映射患者。在后者中,您建议生成器忽略对医生的引用。然后您可以使用@AfterMapping 自定义来设置医生参考。

【讨论】:

    【解决方案2】:

    对于 ManyToOne,请使用注释 JsonManagedReference,对于 OneToMany,请使用 JsonBackReference

    【讨论】:

    • 我已经这样做了,并且在 json 映射中运行良好。但这里不是关于 json 映射的。是关于实体和 dto 之间的映射
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多