Reputation: 146
I want to ask about a good practice to convert Entity with associated entities to DTO's.
So, for example i have 3 enities:
@Entity
@Table
public class First {
@Id
private int id;
@OneToMany(mappedBy = "first")
...
private List<Second> second;
@ManyToOne
...
private Third third;
@Entity
@Table
public class Second {
@Id
private int id;
@ManyToOne
...
private First first;
@OneToMany(mappedBy = "second")
...
private List<Third> third;
@Entity
@Table
public class Third {
@Id
private int id;
@ManyToOne
...
private Second second;
@OneToMany(mappedBy = "third")
...
private List<First> first;
What is the best practice to convert all of these to DTO's? I don't want to use external libraries.
Like you see the problem is with recurrency of it and nested assotations.
Greetings.
Edit: Can somebody give me the names of libraries for mapping DTO used by himself?
Upvotes: 0
Views: 619
Reputation: 96
This might help:
I recommend to use the custom dto to avoid cycles ( causes StackOverFlowError). Advantage to manage the content you are transferring. Using the entity class above, i constructed the dto below.
I have dependency for lombok like
"org.projectlombok" % "lombok" % lombokVersion
in my build.
Constructed my custom DTO
@Data
public class FirstDTO implements Jsonable {
protected String id;
protected ThirdDTO third;
public FirstDTO(){}
@JsonCreator
public FirstDTO(@JsonProperty("id") String id,
@JsonProperty("third") Third third){
this.id = id;
this.third = third;
}
}
Upvotes: 2