提问者:小点点

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


我刚开始在一个项目中使用JPA和JPQL,但是我SQL语法错误,我找不到原因。

我正在使用Spring启动,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个答案

匿名用户

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

public ChoiceVoteCount() {
}

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