【发布时间】:2015-01-27 09:20:27
【问题描述】:
我正在寻找一种使用 Spring Data JPA 动态构建查询的解决方案。我有一个 GameController,它有一个 RESTful 服务端点 /games,它接受 4 个可选参数:流派、平台、年份、标题。 API 可以不通过任何一个,所有 4 个,以及它们之间的每个组合。如果未传递任何参数,则默认为 null。我需要存储库中的一个方法来构建适当的查询,并且理想情况下还允许 Spring Data JPA 分页,尽管我不确定这是否可能。
我找到了这篇文章,但这似乎不是我需要的,除非我误解了。 http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
我知道 JPA 有一个 Query Criteria API,但真的不知道如何实现它。
我意识到我可以为每个可能的场景创建一个方法,但这似乎是一种非常糟糕的做法,并且有很多不必要的代码。
游戏存储库:
package net.jkratz.igdb.repository;
import net.jkratz.igdb.model.Game;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface GameRepository extends JpaRepository<Game, Long> {
@Query("select g from Game g, GamePlatformMap gpm, Platform p where g = gpm.game and gpm.platform = p and p.id = :platform")
Page<Game> getGamesByPlatform(@Param("platform") Long platformId, Pageable pageable);
@Query("select g from Game g where g.title like :title")
Page<Game> getGamesByTitle(@Param("title") String title, Pageable pageable);
@Query("select g from Game g, GameGenreMap ggm, Genre ge where g = ggm.game and ggm.genre = ge and ge.id = :genreId")
Page<Game> getGamesByGenre(@Param("genre") Long genreId, Pageable pageable);
}
【问题讨论】:
标签: spring hibernate jpa spring-data spring-data-jpa