Yes, it is possible to use Spring Data Pageables with unprocessed JDBC queries. You can define the query in the form of a SQL string and pass it to the JdbcTemplate
along with parameters and a RowMapper
, then use the Pageable
interface to specify the page size and current page number. Here is an example:
public Page<Customer> findCustomers(String firstName, Pageable pageable) {
String sql = "SELECT id, first_name, last_name FROM customers WHERE first_name = ?";
List<Customer> customers = jdbcTemplate.query(
sql,
new Object[]{firstName},
new BeanPropertyRowMapper<>(Customer.class)
);
int total = customers.size();
int offset = pageable.getPageNumber() * pageable.getPageSize();
int limit = pageable.getPageSize();
List<Customer> page = customers.subList(offset, Math.min(offset + limit, total));
return new PageImpl<>(page, pageable, total);
}
In this example, we define a SQL query to fetch customers with a given first name, then use the JdbcTemplate
to execute the query and map the result to a list of Customer
objects. We calculate the offset and limit based on the Pageable
object, then extract the page of results from the list using subList()
. Finally, we wrap the page in a PageImpl
object along with the total number of results and return it.
Asked: 2023-06-16 08:25:45 +0000
Seen: 12 times
Last updated: Jun 16 '23