Spring Boot @Query注释countQuery起作用,但countName不起作用

时间:2019-07-13 11:47:18

标签: java spring hibernate spring-boot jpa

我正在尝试使用@Query注释和Spring来执行一些本机查询,但遇到以下问题:

我有一个名为jpa-named-queries.properties的文件,我在其中放置查询,我有一个查询来获取数据,并有一个查询来对数据进行计数。 Ej:

Find.members.team = SELECT ct.id teamId, r.user_id userId, (SELECT SUM(rd.resume_value) FROM resume_detail rd WHERE rd.resume_id = r.id) resumeMemberValue FROM resume r INNER JOIN challenge_team ct ON r.team_id = ct.id WHERE ct.id = :teamId ORDER BY resumeMemberValue ASC
Find.members.team.count = SELECT count(resume.id) FROM resume INNER JOIN challenge_team ct ON resume.team_id = ct.id WHERE ct.id = :teamId

并且我有Repository方法来使用查询:

@Query(name = "Find.members.team", 
       countName= "Find.members.team.count",  
       nativeQuery = true)
Page<TeamMemberProjection> findMembersTeamByIdWithPagination(@Param("teamId") Long id, Pageable pageable);

问题是,如果我如上所述执行,查询执行的是:

Hibernate: SELECT ct.id teamId, r.user_id userId, (SELECT SUM(rd.resume_value) FROM resume_detail rd WHERE rd.resume_id = r.id) resumeMemberValue FROM resume r INNER JOIN challenge_team ct ON r.team_id = ct.id WHERE ct.id = ? ORDER BY resumeMemberValue ASC limit ?
Hibernate: select count(rd) FROM resume_detail rd WHERE rd.resume_id = r.id) resumeMemberValue FROM resume r INNER JOIN challenge_team ct ON r.team_id = ct.id WHERE ct.id = ?

那会导致异常,因为执行的查询没有意义。

但是,如果我使用注释的 countQuery 属性,例如:

@Query(name = "Find.members.team", 
       countQuery= "SELECT count(resume.id) FROM resume INNER JOIN challenge_team ct ON resume.team_id = ct.id WHERE ct.id = :teamId",  
       nativeQuery = true)
Page<TeamMemberProjection> findMembersTeamByIdWithPagination(@Param("teamId") Long id, Pageable pageable);

The queries executed are:
Hibernate: SELECT ct.id teamId, r.user_id userId, (SELECT SUM(rd.resume_value) FROM resume_detail rd WHERE rd.resume_id = r.id) resumeMemberValue FROM resume r INNER JOIN challenge_team ct ON r.team_id = ct.id WHERE ct.id = ? ORDER BY resumeMemberValue ASC limit ?
Hibernate: SELECT count(resume.id) FROM resume INNER JOIN challenge_team ct ON resume.team_id = ct.id WHERE ct.id = ?

那很好。

这些属性的文档说明: countName

Returns the name of the javax.persistence.NamedQuery to be used to execute count queries when pagination is used. Will default to the named query name configured suffixed by .count.

countQuery

Returns the name of the javax.persistence.NamedQuery to be used to execute count queries when pagination is used. Will default to the named query name configured suffixed by .count.

在其他示例中,我同时使用了这两个属性,并且效果很好,但是在这种特殊情况下,我不明白我在做什么错误。

0 个答案:

没有答案