javaspringjdbcspring-dataspring-data-jdbc

How to set fetch-size in Spring-Data-JDBC


I use Spring-Data-JDBC (not JPA) and want to set the fetch-size.

I know that the the classic org.springframwork.jdbc.core.JdbcTemplate has a setFetchSize(int) method, but I have Spring-Data-JDBC repository:

org.springframework.data.repository.Repository;
org.springframework.data.jdbc.repository.query.Query;

/** This is a Spring Data <b>JDBC</b> (JDBC not JPA!). */      
public interface UserDao extends  Repository<User, Long> {
  
    @Query(value = UserRowMapper.SELECT_BY_NAME_STATEMENT
           rowMapperClass = UserRowMapper.class)
    Optional<User> findByName(String name);
}

and this is the relevant part of the configuration:

@Configuration
@EnableJdbcRepositories 
public class AppConfigSpringDataJdbc extends AbstractJdbcConfiguration {
   @Autowired
   private DataSource dataSource;

   @Bean
   public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
       return new NamedParameterJdbcTemplate(this.dataSource);
   }
}

So my question is: How/Where to set the sql query fetch-size when using Spring-Data-JDBC, either by query or in general?

(The common solutions for Spring-Data-JPA will not work, because there is no persistence.xml or javax.persistence.QueryHintannotation because it is JDBC)


Solution

  • You can create NamedParameterJdbcTemplate using custom JdbcTemplate.

    @Bean
    JdbcOperations jdbcOperations(DataSource dataSource) {
        final var jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setFetchSize(100);
        return jdbcTemplate;
    }
    
    @Bean
    NamedParameterJdbcOperations namedParameterJdbcOperations(JdbcOperations operations) {
        return new NamedParameterJdbcTemplate(operations);
    }