【问题标题】:Spring Data JPA JPQL column name is discarded in count function [duplicate]Spring Data JPA JPQL列名在计数函数中被丢弃[重复]
【发布时间】:2019-03-16 04:01:09
【问题描述】:

我有一个使用 Spring Data JPA JPQL 选择一些记录的代码。

我有两个实体:

public class Cheat implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cheat_seq", length = 10)
    private Long cheatSeq;

    @OneToMany(mappedBy = "cheat")
    private Set<CheatGoodVote> goodVote;

    // skipped..
}

public class CheatGoodVote {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="vote_seq", length=10)
    private Long voteSeq;

    @Column(name="ip_address", nullable=false)
    private String ipAddress;

    @Column(name="reg_date", nullable=false)
    private Date regDate;

    @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    @JoinColumn(name="cheat_fk", referencedColumnName="cheat_seq")
    public Cheat cheat;


}

我的存储库很简单:

public interface CheatRepository extends JpaRepository<Cheat, Long>{

    @Query("SELECT c FROM Cheat c WHERE COUNT(c.goodVote) <= :voteCnt")
    Page<Cheat> findByVoteLessThan(@Param("voteCnt") Long voteCnt, Pageable page);
}

当我调用方法CheatRepository.findByVoteLessThan()时, 它在 SQL 下执行。

select 
cheat0_.cheat_seq as cheat_se1_0_, cheat0_.answer as answer2_0_, cheat0_.question as question3_0_, cheat0_.reg_date as reg_date4_0_, cheat0_.writer_ip as writer_i5_0_ 
from cheat cheat0_ cross join cheat_good_vote goodvote1_ 
where cheat0_.cheat_seq=goodvote1_.cheat_fk and count(.)<=? 
order by cheat0_.reg_date desc limit ?

但是在那个 SQL 中,WHERE 子句中有一个奇怪的代码 count(.)。也许这就是引发错误的原因。

面对这个问题的原因可能是什么? 谢谢。

【问题讨论】:

  • 你不能在 where 子句中使用 count... 你需要更改为 having 子句
  • @Alan Hay 谢谢。这是最好的答案
  • @Desorder 这是个好方法。我会考虑那个查询

标签: spring jpa jpql


【解决方案1】:

COUNT 是一个聚合函数,不能在 where 子句中使用。相反,您可以使用 SQL 原生内部查询或有子句。

【讨论】:

  • 感谢您回答我的问题。感谢 Alan Hay 的评论,我找到了正确的方法。
猜你喜欢
  • 2019-05-03
  • 1970-01-01
  • 2020-01-14
  • 2017-11-28
  • 2017-06-23
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2016-07-02
相关资源
最近更新 更多