我得到 1) 错误映射 entity.Team 到 TeamDTO 后跟 java.lang.StackOverflowError: null 没有任何真正的原因或堆栈跟踪中的行。我正在尝试通过 Id 从数据库中获取实体。
实体:
@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:
@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;
}
我在这里获取数据并将其转换为 DTO 以将其返回给 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);
}
所以有人能帮帮我吗??
编辑: 发现我的 TeamDTO 中的这两行导致计算器溢出:
List<MatchDTO> homeTeamMatches = new ArrayList<>();
List<MatchDTO> awayTeamMatches = new ArrayList<>();
如何在不导致计算器溢出的情况下将这些属性映射为两个?
最佳答案
private final ModelMapper modelMapper = new ModelMapper();
在 Spring 上下文中不是一个好的做法。
您需要创建一个单独的配置类,如下所示,
@Configuration
public class AppConfiguration {
@Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}
}
和使用
@Autowired
private final ModelMapper modelMapper;
或在 setter 注入(inject)中。
关于java - Spring Boot 模型映射器 - StackOverflowError : null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64864432/