Java Reference
In-Depth Information
queries in JPA: the Query object. To use JPA's Query API, you need to implement the
org.springframework.batch.item.database.orm.JpaQueryProvider interface. The interface, which
consists of a createQuery() method and a setEntityManager(EntityManager em) method is used by the
JpaPagingItemReader to obtain the required Query to be executed. To make things easier, Spring batch
provides an abstract base class for you to extend, the
org.springframework.batch.item.database.orm.AbstractJpaQueryProvider . Listing 7-52 shows what the
implementation to return the same query (as configured in Listing 7-51) looks like.
Listing 7-52. CustomerByCityQueryProvider
package com.apress.springbatch.chapter7;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.batch.item.database.orm.AbstractJpaQueryProvider;
import org.springframework.util.Assert;
public class CustomerByCityQueryProvider extends AbstractJpaQueryProvider {
private String cityName;
public Query createQuery() {
EntityManager manager = getEntityManager();
Query query =
manager.createQuery("select c from Customer " +
"c where c.city = :city");
query.setParameter("city", cityName);
return query;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(cityName);
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
}
For the CustomerByCityQueryProvider, you use the AbstractJpaQueryProvider base class to handle
obtaining an EntityManager for you. From there, you create the JPA query, populate any parameters in
the query and return it to Spring Batch for execution. To configure your ItemReader to use the
CustomerByCityQueryProvider instead of the query string you provided previously, you simply swap the
queryString parameter with the queryProvider parameter, as shown in Listing 7-53.
Listing 7-53. Using the JpaQueryProvider
<beans:bean id="customerItemReader"
 
Search WWH ::




Custom Search