有人可以帮我解决这个问题吗?我尝试使用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的解决方案。
如果需要任何详细信息,请告诉我。 谢谢!
最佳答案
您有两种映射方法,一种用于映射医生,一种用于映射患者。在后者中,您建议生成器忽略对医生的引用。然后您可以使用 @AfterMapping
自定义来设置医生引用。
关于java - 如何在 Java 中将双向实体映射到 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39702389/