Spring Data JPA:抛出 MethodArgumentTypeMismatchException(字符串不能转换为整数),但请求参数不是字符串类型



我正在构建一个带有crud功能的Spring-REST-API,用于使用内存中的h2数据库创建、读取、更新和删除电影。创建新电影,获取所有电影,通过id获取单个电影,更新电影和删除电影的基本功能都正常工作(我用Postman测试了这个)。

除了这些基本功能,API还应该能够搜索电影的标题,他们的票数,他们的明星数量和发行日期。

首先,我是这样实现电影实体的(使用一些lombok注释来减少样板代码):

@Entity
@Table(name="FILMS")
@Getter
@Setter
@RequiredArgsConstructor
public class Film {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name="TITLE")
private String title;
@Column(name="VOTES_COUNT")
private Integer votesCount;
@Column(name="RELEASE_DATE")
private LocalDate releaseDate;
@Column(name="STARS_COUNT")
private Integer starsCount;
}

My FilmRepository是这样的:

public interface FilmRepository extends CrudRepository<Film, Integer> {
List<Film> findByTitle(String title);
List<Film> findByVotesCount(Integer votesCount);
List<Film> findByReleaseDate(LocalDate releaseDate);
List<Film> findByStarsCount(Integer starsCount);
}

这是controller类中的方法,它应该根据标题、投票数、明星数和上映日期来处理电影搜索:

@RequestMapping("/films")
@RestController
public class FilmController {
private final FilmRepository filmRepository;
public FilmController(final FilmRepository filmRepository) {
this.filmRepository = filmRepository;
}
// some other methods for @GetMapping, @PostMapping and so on...

@GetMapping("/films/search")
@ResponseStatus(HttpStatus.OK)
public List<Film> searchFilms(@RequestParam(name = "title", required = false) String title, @RequestParam(name = "votesCount", required = false) Integer votesCount, @RequestParam(name = "releaseDate", required = false) LocalDate releaseDate, @RequestParam(name = "starsCount", required = false) Integer starsCount) {
if (title != null) {
return this.filmRepository.findByTitle(title);
} else if (votesCount != null) {
return this.filmRepository.findByVotesCount(votesCount);
} else if (releaseDate != null) {
return this.filmRepository.findByReleaseDate(releaseDate);
} else if (starsCount != null) {
return this.filmRepository.findByStarsCount(starsCount);
} else {
return new ArrayList<>();
}
}

我对Postman做了一个POST-Request,这导致了这个数据库条目:

[
{
"id": 1,
"title": "Test",
"votesCount": 5,
"releaseDate": "1998-01-01",
"starsCount": 5
}
]

当我现在尝试对这个URI http://localhost:8080/films/search?title=Test执行GET-Request时,控制台显示以下错误消息

DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; For input string: "search"]

,我得到一个400错误请求。当我尝试例如这个请求http://localhost:8080/films/search?votesCount=5.

时,错误保持不变。为什么我的应用程序假设标题必须转换为整数?我认为我的注释是正确的:

@RequestParam(name = "title", required = false) String title

如果有spring - jpa专家能帮助我就太好了。提前感谢!

如果您发送了这个body请求,那么将@RequestParam("id")Integer id添加到您的searchFilms控制器方法中。这个错误清楚地表明,您首先在请求体中发送id,这就是您得到的异常。如果你没有在requestparam中添加id,那么就从请求体中删除id属性。

[
{
"id": 1,
"title": "Test",
"votesCount": 5,
"releaseDate": "1998-01-01",
"starsCount": 5
}
]

最新更新