gpt4 book ai didi

java - 如何在 Java 中将双向实体映射到 DTO

转载 作者:行者123 更新时间:2023-11-30 10:38:24 24 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?我尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com