【问题标题】:Converting MySQL query into JPA to get count将 MySQL 查询转换为 JPA 以获取计数
【发布时间】:2020-04-22 10:07:03
【问题描述】:

这里我有一个 SQL 查询,它可以很好地从 MySQL 数据库中获取计数,就像

 @Query("SELECT count(is_accepted) as value, post_type, is_accepted from agent_activities where "
+ "YEAR(created_date_time) as year and post_type = 'ticket' " +  "GROUP BY is_accepted")

当我尝试使用 Java 作为 JPA 查询时,它不起作用。

public interface AgentActivitiesRepo extends JpaRepository<AgentActivitiesEntity, Long> {
@Query("select new ProductIssuesModel"
        + "(count(data.isAccepted) as acceptCount) "
        + "from data where YEAR(data.createdDate) as :year "
        + "and data.postType = :postType " + "group by data.isAccepted")

public List<ProductIssuesModel> findAgentActivitiesYearly(Long year, String postType);

}

这里ProductIssuesModel 是这样的:

public class ProductIssuesModel {

private Long acceptCount;
private Long rejectCount;
private Long year;
private Long month;
...}

通过运行上述查询,我​​遇到如下错误:

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: as near line 1, column 137 [select new com.accenture.icoe.fm.model.ProductIssuesModel(count(data.isAccepted) as acceptCount) from data where YEAR(data.createdDate) as :year and data.postType = :postType group by data.isAccepted]

如果您发现任何错误,请告诉我。

【问题讨论】:

  • 你认为 'where YEAR(data.createdDate) = :year' 而不是 'where YEAR(data.createdDate) as :year'?

标签: java mysql spring-data-jpa


【解决方案1】:

有两种编写 JPQL 的方法 -


  1. 索引查询参数
@Query("select new ProductIssuesModel"
        + "(count(data.isAccepted) as acceptCount) "
        + "from data where YEAR(data.createdDate) = ?1 "
        + "and data.postType = ?2 " + "group by data.isAccepted")

public List<ProductIssuesModel> findAgentActivitiesYearly(Long year, String postType);

参数的值将根据位置/索引绑定到查询。


  1. 命名参数
@Query("select new ProductIssuesModel"
        + "(count(data.isAccepted) as acceptCount) "
        + "from data where YEAR(data.createdDate) = :year "
        + "and data.postType = :postType " + "group by data.isAccepted")

public List<ProductIssuesModel> findAgentActivitiesYearly(@Param("year") Long year, @Param("postType") String postType);

在你的情况下,第二种方法是适用的。

【讨论】:

    【解决方案2】:

    这里,YEAR(data.createdDate) as :year 不是条件表达式。

    您可以尝试这样做YEAR(data.createdDate) = :year。 并使用@Param 在JPQL 中使用参数

    @Query("select new ProductIssuesModel"
            + "(count(data.isAccepted) as acceptCount) "
            + "from data where YEAR(data.createdDate) = :year "
            + "and data.postType = :postType " + "group by data.isAccepted")
    public List<ProductIssuesModel> findAgentActivitiesYearly(@Param("year") Long year, @Param("postType") String postType);
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2012-09-28
      • 2011-06-17
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2019-01-11
      相关资源
      最近更新 更多