Spring Boot バックエンドでのフィルタリングの実装
温馨提示:
本文最后更新于 2024年04月12日,已超过 48 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
I'm encountering an issue with applying a filter to a table in the backend using Java Spring Boot. I'm receiving a list of games with various attributes including mechanisms.
{
"id_game": 1,
"code": "DR54HY",
"name": "Name",
"age": 4,
"price": 29,
"description": "Description",
"nbGamer": 2,
"mechanisms": [
{
"id_mechanism": 1,
"name": "Card"
},
{
"id_mechanism": 2,
"name": "Adventure"
}
],
}, //etc
I'm trying to implement a filter to retrieve games based on specific mechanisms name. However, the current implementation is not working as expected. When I try to retrieve games based on multiple mechanisms, it doesn't filter the games properly. Here's the code:
GameRepository.java:
@Repository
public interface GameRepository extends JpaRepository<Game, Integer> {
Page<Game> findAll(Pageable pageable);
Page<Game> findAllByMechanismsName(Pageable pageable, List<String> mechanismsName);
}
GameService.java:
@Service
public class GameService {
@Autowired
private GameRepository gameRepository;
public Page<Game> getGames(Pageable pageable, List<String> mechanismsName) {
if (mechanismsName != null) {
return gameRepository.findAllByMechanismsName(pageable, mechanismsName);
} else {
return gameRepository.findAll(pageable);
}
}
GameController.java:
@RestController
public class GameController {
@Autowired
private GameService gameService;
@GetMapping("/games")
public ResponseEntity<Page<Game>> getGames(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam(required = false) List<String> mechanismsName
) {
Pageable pageable = PageRequest.of(page, pageSize);
Page<Game> gamesPage = gameService.getGames(pageable, mechanismsName);
if (gamesPage.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(gamesPage, HttpStatus.OK);
}
}
Here's the Postman request:
GET /games?page=0&pageSize=10&mechanismsName=Card
or
GET /games?page=0&pageSize=10&mechanismsName=Card,Power
正文到此结束
- 本文标签: 家庭宠物
- 本文链接: https://www.coder6.net/article/2456
- 版权声明: 本文由蚂蚁原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
-
浏览(193) 评论(0)