Ask Your Question
4

Is it possible to utilize Spring Data Pageables in combination with unprocessed JDBC queries?

asked 2023-06-16 08:25:45 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-16 08:42:02 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-16 08:25:45 +0000

Seen: 12 times

Last updated: Jun 16 '23