在JPA中实现分页的正确方法是什么?

时间:2013-02-01 20:52:42

标签: spring hibernate jpa paging entitymanager

我查看了this问题的一些细节,但我仍然在实现分页时遇到问题。我认为这可能与我的实体经理的设置方式有关。

我正在使用Spring来配置应用程序;这是相关的弹簧配置(必须删除一些细节):

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">


    <import resource="classpath:core-infrastructure-context.xml" />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="persistenceUnit" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="packagesToScan" value="domain" />
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider</prop>
                <prop key="hibernate.max_fetch_depth">3</prop>
                <prop key="hibernate.jdbc.fetch_size">100</prop>
                <prop key="hibernate.jbc.batch_size">1000</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.use_sql_comments">false</prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="databaseMarshaller" >
        <property name="pageSize" value="100"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="validationQuery" value=""/>
        <property name="testWhileIdle" value="false"/>
    </bean>

</beans>

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="persistenceUnit">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
    </persistence-unit>

</persistence>

这是调用的方法,它试图完成分页:

public void execute(){

    createBaseDir(); //creates a directory on the filesystem

    File domainDir = createDomainDir(); //creates a subfolder of the directory created above

    Long numRows = countRows(); //implementation provided below


    //Here is where I'm trying to page
    //em is an EntityManager injected by Spring using @PersistenceContext
    CriteriaBuilder cb = em.getCriteriaBuilder();

    //IEntity is a custom interface that all managed entities inherit from.
    //clazz is the FQCN of the managed entity I am querying for
    CriteriaQuery<IEntity<?>> cq = cb.createQuery(clazz);
    Root<IEntity<?>> c = cq.from(clazz);
    cq.select(c);
    cq.orderBy(cb.asc(c.get("id")));
    TypedQuery<IEntity<?>> entityQuery = em.createQuery(cq);

    //pageSize = 100, injected from Spring
    for(int row = 0; (row + pageSize) < numRows || numRows-row > 0; row+=pageSize){

        entityQuery = em.createQuery(cq);
        entityQuery.setFirstResult(row);
        int maxResults = (row+pageSize > numRows)?numRows.intValue():row+pageSize;
        entityQuery.setMaxResults(maxResults);



        //This call grows by pageSize every iteration instead of returning only #pageSize records
        List<IEntity<?>> entities = entityQuery.getResultList(); 

        marshallToFile(entities, domainDir);//Uses jaxb to marshall domain objects to file

    }
}

private Long countRows(){
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
    //clazz is the FQCN of the managed entity I am querying for
    countQuery.select(builder.count(countQuery.from(clazz)));
    Long count = em.createQuery(countQuery).getSingleResult();
    return count;
}

问题在于,在for循环的每次迭代中,对entityQuery.getResultList();的调用会向结果列表添加100多行,而不是返回仅包含100行的列表。我使用调试器,setFirstResultsetMaxResults正常工作(第一次迭代它们是0,100;然后是100,200;然后是200,300;等等......)但返回的列表大小每次都增长。

有人知道我的问题是什么吗?

1 个答案:

答案 0 :(得分:1)

卫生署!发现我在逻辑上的缺陷......:/

  

我使用调试器并且setFirstResultsetMaxResults正常工作(第一次迭代它们是0,100;然后是100,200;然后是200,300;等等......)。

这不正确......它应该是0,100;那么100,100;然后200,100;等...

无论如何,不​​得不改变这一行: int maxResults = (row+pageSize > numRows)?numRows.intValue():row+pageSize; 对此: int maxResults = (row+pageSize > numRows)?numRows.intValue():pageSize;

现在它有效。猜猜我会把这个作为一个例子让其他人知道如何让分页工作。