2016-09-26 138 views
2

有人可以幫我解決這個問題嗎?我嘗試過使用maptruct,它工作得很好,但只適用於沒有雙向關係的實體。如何在Java中將雙向實體映射到DTO

比如我有實體:

@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的解決方案。

如果需要任何細節,請讓我知道。 謝謝!

+2

Java和Entity Framework在同一個問題中。你確定嗎? – DavidG

+0

你說得對。我將重點放在如何提出問題以儘可能清楚。謝謝! – Aditzu

+0

我假設你的Dtos應該互相引用,即'PacientsDto'不應該引用'Doctors',而應該指向'DoctorsDto',並且'DoctorsDto'也是相同的。 – Dominik

回答

0

請使用標註爲JsonManagedReference和多對一的JsonBackReference一對多

+1

我已經做到了這一點,併爲json映射工作。但這裏不是關於json映射。是關於實體和dto之間的映射 – Aditzu

0

Hibernate's forum這也與無限循環的問題的問題。這到底是工作的解決方案是:

  • @IdClass
  • @Idmain
  • 做你@ManyToOne在PK類,並讓fetchType=LAZY
  • 充分利用fetchType=LAZY@OneToMany
  • 註釋
+1

問題與休眠無關。我可以從數據庫加載沒有任何問題的數據。我更大的問題是,我無法將實體映射到Dto – Aditzu

1

你會有兩種映射方法,一種用於映射醫生,一種用於映射 耐心。在後者中,你建議生成器忽略對醫生的引用。然後,您可以使用@AfterMapping自定義設置醫生參考。