Преобразование MySQL запроса в JPA для подсчета - PullRequest
0 голосов
/ 22 апреля 2020

Здесь у меня есть запрос 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]

Пожалуйста, дайте мне знать, если вы видите какую-либо ошибку.

Ответы [ 2 ]

0 голосов
/ 22 апреля 2020

Существует два способа написания 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);

Значения параметров будут привязаны к запросу на основе позиции / индекса.


Именованные параметры
@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);

В вашем случае применим второй подход.

0 голосов
/ 22 апреля 2020

Здесь 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...