如何在spring-data-jpa中使用DISTINCT,GROUP BY,ORDER BY?

时间:2017-10-09 13:24:09

标签: java spring jpa spring-data spring-data-jpa

小心:此问题被错误地标记为重复。无论如何,我找到了一个解决方案,我将在下面的问题中添加,因为无法在“重复”问题上发布答案。

我想使用sql和spring-data-jpa将以下JPA查询转换为querydsl查询:

SELECT DISTINCT age FROM `my_table`
  WHERE firstname = 'john' AND lastname = 'doe'
  GROUP BY age
  ORDER BY COUNT(*) DESC
  LIMIT 1

目前我有以下内容,它只选择第一个+姓氏的所有条目:

public interface MyRepository extends JpaRepository<MyEntity, Long>, QueryDslPredicateExecutor<MyEntity> {

}

用法:

@Autowired
private MyRepository dao;

//select * from my_table where firstname = ? and lastname = ?
BooleanExpression query = p.firstname.eq(firstname).and(p.lastname.eq(lastname));
dao.findAll(query);

//TODO how to add group, order and limit?

但我现在想要按age字段进行分组,并选择最常出现的年龄。但是如何在querydsl中添加DISTINCTGROUP BYORDER BY COUNTLIMIT语句?

解决方案:无法直接使用CrudRepository,但仍可轻松使用com.querydsl.jpa.impl.JPAQuery,如下所示:

QPersonEntity p = QPersonEntity.person; //the querydsl definition

int age = new JPAQuery(em)
    .select(p.age)
    .from(p)
    .where(p.firstname.eq(firstname).and(p.lastname.eq(lastname)))
    .groupBy(p.age)
    .orderBy(p.age.count().desc())
    .limit(1)
    .fetchOne();

1 个答案:

答案 0 :(得分:1)

您可以在@Repository中定义方法,以便公开使用本机查询执行所需操作的方法。实际上,正如Spring Data JPA参考文档中的报告:

  

@Query注释允许通过设置执行本机查询   nativeQuery标志为true。

您可以在@Repository

中添加此代码段
@Query(value = "SELECT DISTINCT age "+
               "FROM my_table "+
               "WHERE firstname = :firstname AND lastname = :lastname " +
               "GROUP BY age " +
               "ORDER BY COUNT(*) DESC " +
               "LIMIT 1", nativeQuery = true)
int retrieveAgeByFirstNameAndLastName(@Param("firstname") String firstname,
                                      @Param("lastname") String lastname);