简体   繁体   English

JPA:使用投影返回自定义 object

[英]JPA: Return custom object using projection

I have this code in SponsorRepository which extends JpaRepository<Sponsor, Long> ...我在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);

The problem is that when running the server it gives me an error saying that the id was not found.问题是,在运行服务器时,它给了我一个错误,说找不到 id。 I researched into this and found that I am making the function return a list of sponsors, even though the query itself is return a fundraiser name and amount.我对此进行了研究,发现我正在让 function 返回赞助商列表,即使查询本身返回筹款人名称和金额。 Also, JPA cannot map this into a list of sponsor.此外,JPA 不能将 map 列入赞助商名单。 I was advised to use JPA projection.有人建议我使用 JPA 投影。 What are the steps I need to take to do so?我需要采取哪些步骤才能这样做? Would projection be the solution or a RestController ?投影是解决方案还是RestController

Create new protection interface for your result tuple:为您的结果元组创建新的保护接口:

public interface SponsorProjection {    
    String getName();
    Long getAmount();
}

Then add aliases and change the return type:然后添加别名并更改返回类型:

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

Your controller will look like this:您的 controller 将如下所示:

@RestController
public class SponsorController {

    @Autowired
    private SponsorRepository repo;

    @GetMapping(path = "/findTopFiveSponsors")
    public ResponseEntity<?> get(@Param("charityId") Long charityId) {
        return ResponseEntity.ok(repo.findTopFiveSponsors(charityId));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM