【问题标题】:How do I convert this JPQL to CriteriaBuilder on H2?如何在 H2 上将此 JPQL 转换为 CriteriaBuilder?
【发布时间】:2016-01-16 12:40:55
【问题描述】:

我正在尝试转换此查询

@Query( "select l from Log l order by l.created desc, l.entry asc " )
Page<Log> findAllCustomJpql( Pageable pageable );

生成这个 sql

Hibernate: select count(log0_.id) as col_0_0_ from log log0_
Hibernate: select log0_.id as id1_0_, log0_.created as created2_0_, log0_.entry as entry3_0_ from log log0_ order by log0_.created desc, log0_.entry asc limit ?

到标准构建器查询,使用规范

@RequestMapping( method = RequestMethod.GET, path = "spec")
Page<Log> getLogsBySpecification( final Pageable pageable ) {
    return repository.findAll( ( root, query, cb ) -> {
        query.orderBy(
                cb.desc( root.get( "created" ) ),
                cb.asc( root.get( "entry" ) )
        );
        return null;
    }, pageable);
}

它正在执行以下操作

2015-10-17 19:33:40.720  WARN 10498 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 90016, SQLState: 90016
2015-10-17 19:33:40.721 ERROR 10498 --- [nio-8080-exec-6] 
o.h.engine.jdbc.spi.SqlExceptionHelper   : Column "LOG0_.ENTRY" must be in the GROUP BY list; SQL statement:
select count(log0_.id) as col_0_0_ from log log0_ order by log0_.created desc, log0_.entry asc [90016-188]
2015-10-17 19:33:40.750 ERROR 10498 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.h2.jdbc.JdbcSQLException: Column "LOG0_.ENTRY" must be in the GROUP BY list; SQL statement:
select count(log0_.id) as col_0_0_ from log log0_ order by log0_.created desc, log0_.entry asc [90016-188]

我个人认为 sql 是有效的,如果不建议的话,但似乎对 h2 无效。如何更正我的标准以生成我想要的结果?

【问题讨论】:

    标签: java spring-data spring-data-jpa h2 criteria-api


    【解决方案1】:

    这确实不是同一个查询,但我相信它会产生相同的效果。

    @RequestMapping( method = RequestMethod.GET, path = "spec" )
    Page<Log> getLogsBySpecification( final Pageable pageable ) {
        return repository.findAll( ( root, query, cb ) -> {
            query.orderBy(
                    cb.desc( root.get( "created" ) ),
                    cb.asc( root.get( "entry" ) )
            );
    
            query.groupBy( root.get( "id" ) );
            return null;
        }, pageable );
    }
    

    我有点想知道规范继续应用订单的事实是否是一个错误......最终这似乎与this bug有关

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 2019-07-13
      • 1970-01-01
      • 2021-04-11
      • 2016-07-06
      • 2014-01-17
      • 2011-07-05
      • 2021-10-09
      • 2019-07-03
      相关资源
      最近更新 更多