如何使用JPA @Query注释定义自定义查询

时间:2016-05-19 19:57:50

标签: java spring jpa

如何使用JPA https://www.example.com/login表示法?我希望运行查询:

@Query

我有存储库:

SELECT region, winner_count
FROM awards_regions
WHERE award_id = ?
ORDER BY region

我的实体Java bean是

public interface AwardsRegionsRepository extends JpaRepository<AwardRegion,AwardRegionPk>{

    List<AwardRegion> findAllByOrderByAwardRegionPk_RegionAscSortKeyAsc();
    List<AwardRegion> findByAwardRegionPk_RegionOrderBySortKeyAsc(String region);

    @Query("select a.region, a.winner_count from awards_regions a "
            + "where a.award_id = :awardId order by a.region")
    List<AwardRegion> findByAwardRegionPk_AwardId(@Param("awardId") Long awardId);

}

...和嵌入式PK

@Entity
public class AwardRegion implements Serializable{

    @EmbeddedId
    private AwardRegionPk awardRegionPk;

    @Column(name = "award")
    private String award;

    @Column(name = "sort_key")
    private String sortKey;

    @Column(name = "winner_count")
    private String winnerCount;

}

1 个答案:

答案 0 :(得分:0)

看起来好像是在JPA查询中使用数据库表列名。使用Java bean名称。

public interface AwardsRegionsRepository extends JpaRepository<AwardRegion,AwardRegionPk>{

    List<AwardRegion> findAllByOrderByAwardRegionPk_RegionAscSortKeyAsc();
    List<AwardRegion> findByAwardRegionPk_RegionOrderBySortKeyAsc(String region);

    @Query("select a.awardRegionPk.region, a.winnerCount from AwardRegion a "
            + "where a.awardRegionPk.awardId = :awardId order by a.awardRegionPk.region")
    List<AwardRegion> findByAwardRegionPk_AwardId(@Param("awardId") Long awardId);

}