【问题标题】:How to use pagination on queries in Hibernate with Java based configuration如何使用基于 Java 的配置在 Hibernate 中对查询使用分页
【发布时间】:2018-06-27 22:42:08
【问题描述】:

这是我的休眠配置:

@Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(final DataSource dataSource,
            final Environment env)
    {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("...");

        final Properties jpaProperties = new Properties();

        jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
        jpaProperties.put("hibernate.ejb.naming_strategy", env.getRequiredProperty("hibernate.ejb.naming_strategy"));
        jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
        jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

现在我想使用标准分页设置(如偏移量和限制)在 HQL 中(使用 @Query(value = "query"))进行查询。我知道query.setMaxResults()query.setFirstResult(),但为此我需要Session(或者我需要吗?),但我没有使用会话来配置休眠。

我可以仅使用注释来指定查询的偏移量和限制吗?有没有办法使用HQL以编程方式模拟query.setMaxResults()query.setFirstResult()

【问题讨论】:

  • Sprint 数据在后台管理休眠会话。如果你愿意,你可以得到一个 hibernateTemplate 来执行手动查询,但是既然 Spring 数据提供了分页查询,你为什么不使用它呢?
  • @akuma8 你的意思是PagePageRequest 对象?
  • 是的,还有你的仓库可以实现的接口PagingAndSortingRepository<T,ID>来启用分页和排序。
  • @akuma8 谢谢,会试试的。

标签: java spring hibernate jpa


【解决方案1】:

以下代码可能会对您有所帮助。

public Page<Product> findAll(Pageable pageable){
    //custom page
    PageRequest customPageable = new PageRequest(pageable.getPageNumber(), 100);
    return productRepository.findAll(customPageable);     
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2017-06-14
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多