1

How do you use the JPA @Query notation? I wish to run the query:

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

I have the repository:

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);

}

My entity Java beans are

@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;

}

...and embedded PK

@Embeddable
public class AwardRegionPk implements Serializable{

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

    @Column(name = "award_id")
    private Long awardId;

}
dur
  • 15,689
  • 25
  • 79
  • 125

1 Answers1

0

It looks as though you are using the database table column names in your JPA query. Use the Java bean names.

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);

}
mhatch
  • 4,441
  • 6
  • 36
  • 62