如何修复使用group by解析JPQL的语法错误

时间:2019-03-27 08:39:56

标签: java jpa jpql

我是一个使用JPA和JPQL进行项目开发的新手,但是我遇到了SQL语法错误,找不到原因。

我正在使用Spring Boot,MySQL。

我有一个投票库

public interface VoteRepository extends JpaRepository<Vote, Long> {
    ....

    @Query(value = "SELECT NEW com.self.polls.model.ChoiceVoteCount(v.choice.id, count(v.id)) FROM Vote v WHERE v.poll.id = :pollId GROUP BY v.choice.id", nativeQuery = true)
    List<ChoiceVoteCount> countByPollIdGroupByChoiceId(@Param("pollId") Long pollId);

    ....
}

ChoiceVoteCount

public class ChoiceVoteCount {
     private Long choiceId;

    private Long voteCount;    
}

投票

public class Vote {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "poll_id", nullable = false)
    private Poll poll;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "choice_id", nullable = false)
    private Choice choice;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;
}

但是运行此查询时出现错误

2019-03-27 16:01:34.783 ERROR 68064 --- [nio-5000-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper   : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.self.polls.model.ChoiceVoteCount(v.choice.id, count(v.id)) FROM Vote v WHERE v.' at line 1
2019-03-27 16:01:34.787 ERROR 68064 --- [nio-5000-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.self.polls.model.ChoiceVoteCount(v.choice.id, count(v.id)) FROM Vote v WHERE v.' at line 1

1 个答案:

答案 0 :(得分:0)

您必须在ChoiceVoteCount中添加一个构造函数。
为了安全起见,还可以添加默认构造函数。

public ChoiceVoteCount() {
}

public ChoiceVoteCount(Long choiceId, Long voteCount) {
    this.choiceId = choiceId;
    this.voteCount = voteCount;
}