【发布时间】: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 这是个好方法。我会考虑那个查询