Im getting 1) Error mapping entity.Team to TeamDTO followed by java.lang.StackOverflowError: null without any really cause or line in the stacktrace. Im trying to fetch an entity from database by Id.
Entity:
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Team implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String teamName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_league", referencedColumnName = "id", nullable = false)
private League league;
@OneToMany(mappedBy="homeTeam")
List<Match> homeTeamMatches = new ArrayList<>();
@OneToMany(mappedBy="awayTeam")
List<Match> awayTeamMatches = new ArrayList<>();
@Column(name = "created_at", nullable = false, updatable = false)
private Date createdAt;
@Column(name = "updated_at", nullable = false)
private Date updatedAt;
public Team(String teamName, League league) {
this.teamName = teamName;
this.league = league;
}
@PrePersist
private void createdAt() {
this.createdAt = new Date();
this.updatedAt = new Date();
}
@PreUpdate
private void updatedAt() {
this.updatedAt = new Date();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Team team = (Team) o;
return id.equals(team.id) &&
teamName.equals(team.teamName);
}
@Override
public int hashCode() {
return Objects.hash(id, teamName);
}
}
DTO for the Entity:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({"homeTeamMatches", "awayTeamMatches", "league"})
public class TeamDTO {
private Long id;
private String teamName;
private LeagueDTO league;
List<MatchDTO> homeTeamMatches = new ArrayList<>();
List<MatchDTO> awayTeamMatches = new ArrayList<>();
private Date createdAt;
private Date updatedAt;
}
Here Im fetching the data and converting to DTO to return it back to the controller:
private final TeamRepository teamRepository;
private final ModelMapper modelMapper = new ModelMapper();
public TeamService(@Autowired TeamRepository teamRepository) {
this.teamRepository = teamRepository;
}
public TeamDTO findById(Long id) {
return convertToCategoryDTO(teamRepository.findById(id).get());
}
private TeamDTO convertToCategoryDTO(Team team) {
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE);
return modelMapper
.map(team, TeamDTO.class);
}
So can anyone help me??
EDIT: Found out that this two lines in my TeamDTO causes the stackoverflow:
List<MatchDTO> homeTeamMatches = new ArrayList<>();
List<MatchDTO> awayTeamMatches = new ArrayList<>();
How to map these properties two without causing an stackoverflow?