代码之家  ›  专栏  ›  技术社区  ›  Tom

JPQL的Spring Boot JPA“验证查询失败”错误

  •  1
  • Tom  · 技术社区  · 8 年前

    我试着在jpa中使用一个自定义查询(不是nativeQuery,因为我想将结果映射到一个自定义对象),但我不知道出了什么问题。

    @Repository
    public interface ChallengeCompletionRepository extends JpaRepository<ChallengeCompletion, Integer>{
        List<ChallengeCompletion> findByUser(int uid);
        List<ChallengeCompletion> findByChallenge(int cid);
        List<ChallengeCompletion> findByUserAndChallenge(int uid, int cid);
    
        @Query(value = "SELECT new com.some.rly.long.package.name.ChallengeScore(user_id, count(id)) " +
            "FROM ChallengeCompletion " +
            "WHERE challenge_id = :cid " +
            "GROUP BY user_id " +
            "ORDER BY count(id) DESC")
       List<ChallengeScore> fetchUserScoreForChallenge(@Param("cid") int cid);
    }
    

    @Data
    @NoArgsConstructor
    public class ChallengeScore {
    
        public ChallengeScore(UUID userId, int score){
            this.score = score;
            this.userId = userId;
        }
    
        private int score;
        private User user;
    
        @JsonIgnore
        private UUID userId;
    
    }
    

    @Entity
    @Data
    @Table(name = "challenge_completions")
    public class ChallengeCompletion extends BaseModel{
    
        @ManyToOne
        @JsonBackReference
        private User user;
    
        @ManyToOne
        private Challenge challenge;
    
        @ManyToOne
        private Project project;
    
    }
    

    基本模型为:

    @MappedSuperclass
    @Data
    public abstract class BaseModel {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
    
        @CreationTimestamp
        private Timestamp createdAt;
    
        @UpdateTimestamp
        private Timestamp updatedAt;
    }
    

    错误只是:“查询验证失败…”。我还觉得有点奇怪,我需要为我要构造的类使用完全限定名,。。但这可能是因为这个班不是一个真正的 @Entity 不会自动加载。

    可以在此处找到完整的堆栈跟踪: https://pastebin.com/MjP0Xgz4

    干杯

    编辑:多亏了@DN1的评论,我可以在发现你确实可以做类似的事情后让它工作 cc.challenge.id 如果您不想给出质询对象,而只想给出id:

    @Query(value = "SELECT new com.energiedienst.smartcity.middleware.module.challenge.model.ChallengeScore(cc.user, count(cc.id)) " +
            "FROM ChallengeCompletion cc " +
            "WHERE cc.challenge.id = :cid " +
            "GROUP BY cc.user " +
            "ORDER BY count(cc.id) DESC")
    List<ChallengeScore> fetchUserScoreForChallenge(@Param("cid") int cid);
    

    @Data
    @NoArgsConstructor
    public class ChallengeScore {
    
        public ChallengeScore(User user, long score){
            this.score = score;
            this.user = user;
        }
    
        private long score;
        private User user;
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   user8558216 user8558216    8 年前

    出现异常的原因是您使用的是JPQL,而JPQL使用类/字段名,而不是表/列名(SQL使用的名称)。这个 user_id challenge_id 看起来是列名,您需要更改它们以使用字段名。看见 this guide