简体   繁体   中英

JPA: Return custom object using projection

I have this code in SponsorRepository which extends 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. 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. Also, JPA cannot map this into a list of sponsor. I was advised to use JPA projection. What are the steps I need to take to do so? Would projection be the solution or a 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:

@RestController
public class SponsorController {

    @Autowired
    private SponsorRepository repo;

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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