2

Can someone help me with this problem? I tried with mapstruct and it works just fine but only for entities which doesn't have bidirectional relationship.

For instance I have the entities:

@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
}

and

@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's:

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
}

When I try to map them on dto's I get an StackOverflowError because of that birectional relationship.

Any idea how can I solve this? I will also accept a solution without using mapstruct.

If any details needed please let me know. Thank you!

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Aditzu
  • 696
  • 1
  • 14
  • 25
  • 2
    Java and Entity Framework in the same question. Are you sure about that? – DavidG Sep 26 '16 at 12:08
  • You're right. I was to focus on how to put the question in order to be as clear as possible. Thanks! – Aditzu Sep 26 '16 at 12:12
  • I assume that your Dtos should refer to each other, i.e. the `PacientsDto` should not have a reference to `Doctors` but to `DoctorsDto` and the same for the `DoctorsDto`. – Dominik Nov 01 '16 at 00:52

2 Answers2

3

You'd have two mapping methods, one for mapping doctors and one for mapping patients. In the latter you advice the generator to ignore the reference to doctors. Then you can use an @AfterMapping customization to set the doctors reference afterwards.

Gunnar
  • 18,095
  • 1
  • 53
  • 73
0

Please use annotations JsonManagedReference for ManyToOne and JsonBackReference for OneToMany

  • 1
    I already did that and is working well for json mapping. But here is not about the json mapping. Is about mapping between an entity and a dto – Aditzu Sep 26 '16 at 12:13