我在SponsorRepository
中有此代码,扩展了JpaRepository<Sponsor, Long>
...
@Query(value = "SELECT s.fundraiser_name, d.amount_in_pence/100" +
" FROM sponsor_form s INNER JOIN donation d ON s.id = d.sponsor_form_id " +
"WHERE d.charity_id = :charityId ORDER BY d.amount_in_pence*100 DESC LIMIT 5", nativeQuery =
true)
public List<Sponsor> findTopFiveSponsors(@Param("charityId") Long charityId);
问题是,在运行服务器时,它给我一个错误,提示未找到该ID。我对此进行了研究,发现即使查询本身返回的是筹款人的名称和金额,我仍在使函数返回发起人的列表。而且,JPA无法将此映射到赞助商列表中。建议我使用JPA投影。我需要采取哪些步骤?投影是解决方案还是RestController
?
为结果元组创建新的保护界面:
public interface SponsorProjection {
String getName();
Long getAmount();
}
然后添加别名并更改返回类型:
@Query(value = "SELECT s.fundraiser_name as name, d.amount_in_pence/100 as amount " +
"FROM sponsor_form s INNER JOIN donation d ON s.id = d.sponsor_form_id " +
"WHERE d.charity_id = :charityId " +
"ORDER BY d.amount_in_pence * 100 DESC LIMIT 5", nativeQuery = true)
public List<SponsorProjection> findTopFiveSponsors(@Param("charityId") Long charityId);
您的控制器将如下所示:
@RestController
public class SponsorController {
@Autowired
private SponsorRepository repo;
@GetMapping(path = "/findTopFiveSponsors")
public ResponseEntity<?> get(@Param("charityId") Long charityId) {
return ResponseEntity.ok(repo.findTopFiveSponsors(charityId));
}
}