How do I create DTOs for nested entities referencing each other?

Viewed 39

Lets say if I have two entities like this,

Users Entity:

public class Users {
  @Basic
  @Column(name = "USER_NAME")
  private String name;

  @Basic
  @Column(name = "USER_ADDRESS")
  private String address;

  @ManyToOne
  @JsonBackReference
  @JoinColumn(name = "PERSON_ID")
  private Person personData;
}

Person Entity:

public class Person {
  @Id
  @Column(name = "PERSON_ID")
  private Long personId

  @Basic
  @Column(name = "USER_ADDRESS")
  private String address;

  @OneToMany(mappedBy="personData", cascase = CascadeType.ALL, orphanRemoval = true)
  @JsonManagedReference
  List<Users> users;
}

Now, how do I create DTOs for these two entities when I am doing unit testing? Also, when I try to access these entities in my service, it gives me StackOverflow Exception because of nested entities.

1 Answers

When I try to access these entities in my service, it gives me StackOverflow Exception because of nested entities.

This should have been the case before you have added the annotations @JsonManagedReference and @JsonBackReference. If the SO error continues with those annotations then there is some other issue with your entities and not related with those nested fields.

Now, how do I create DTOs for these two entities when I am doing unit testing?

The same way you have your now entities but you do one of the following:

  • You place again the annotations @JsonManagedReference and @JsonBackReference on those DTOs same way you have them in your entities.

  • You break the relationship into a one sided relationship. So for example UsersDto does not have a field of personData or PersonDto does not have the List<UsersDto> users.

However DTOs usually bring some more functionality in the table in order to consider using them. Just such small issue of stack overflow could be easily avoided only with the above annotations directly on entities.

Related