简体   繁体   English

我如何在 spring jdbcTemplate 中实现分页

[英]how can i implement a pagination in spring jdbcTemplate

here is my following dao implementaion这是我的以下 dao implementationaion

@Override
    public List<UserAddress> getAddresses(int pageid,int total) {

        String sql = "select * FROM user_addresses order by id desc limit "+(pageid-1)+","+total;
        List<UserAddress> userAddresses  = jdbcTemplate.query(sql, new RowMapper<UserAddress>() {
            @Override
            public UserSessionLog mapRow(ResultSet rs, int rowNum) throws SQLException {
                UserAddress userAdd = new UserAddress();
                userAdd.setId(rs.getInt("id"));
                userAdd.setId(rs.getString("city"));
                return userSession;
            }
        });
        return userAddresses;
    }

in the above dao implementaion, i list all the user addresses, trying to list with limit在上面的dao实现中,我列出了所有用户地址,试图以限制列出

@RequestMapping("/userAddresses/{pageid}")
       public ModelAndView userAddresses(@PathVariable int pageid) {
        int total=5;  
        if(pageid==1){}  
        else{  
            pageid=(pageid-1)*total+1;  
        }  
         List<UserAddress> listAddresses = userAddressFacade.getAddresses(pageid,total);
         return new ModelAndView("userAddresses", "listAddresses", listAddresses);
    }

this is my view part,这是我的观点部分,

<table class="table table-condensed">
        <thead>
            <tr>
                <th>Address1</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            <c:if test="${not empty addresses}">
                <c:forEach var="address" items="${addresses}">
                    <tr>
                        <td>${address.address1}</td>
                        <td>${address.city}</td>
                    </tr>
                </c:forEach>
            </c:if>
        </tbody>
    </table>

     <br/>  
   <a href="/pro/userAddress/1">1</a>   
   <a href="/pro/userAddress/2">2</a>   
   <a href="/pro/userAddress/3">3</a>  

I have hardcoded the pagination part, do any one have idea, how to do pagination.我已经对分页部分进行了硬编码,有没有人有想法,如何进行分页。 i am newbie to java jdbcTemplate,我是 java jdbcTemplate 的新手,

This can be done as long as your database supports LIMIT and OFFSET .只要您的数据库支持LIMITOFFSET ,就可以做到这一点。

An example is given here . 这里给出一个例子。 The critical code is shown below (you can ignore the fluent builder clauses):关键代码如下所示(您可以忽略 fluent builder 子句):

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class DemoRepository {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public DemoRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Demo> findDemo() {
        String querySql = "SELECT name, action, operator, operated_at " +
                "FROM auditing " +
                "WHERE module = ?";
        return jdbcTemplate.query(querySql, new Object[]{Module.ADMIN_OPERATOR.getModule()}, (rs, rowNum) ->
                Demo.builder()
                        .rowNum(rowNum)
                        .operatedAt(rs.getTimestamp("operated_at").toLocalDateTime())
                        .operator(rs.getString("operator"))
                        .action(rs.getString("action"))
                        .name(rs.getString("name"))
                        .build()
        );
    }

    public Page<Demo> findDemoByPage(Pageable pageable) {
        String rowCountSql = "SELECT count(1) AS row_count " +
                "FROM auditing " +
                "WHERE module = ? ";
        int total =
                jdbcTemplate.queryForObject(
                        rowCountSql,
                        new Object[]{Module.ADMIN_OPERATOR.getModule()}, (rs, rowNum) -> rs.getInt(1)
                );

        String querySql = "SELECT name, action, operator, operated_at " +
                "FROM auditing " +
                "WHERE module = ? " +
                "LIMIT " + pageable.getPageSize() + " " +
                "OFFSET " + pageable.getOffset();
        List<Demo> demos = jdbcTemplate.query(
                querySql,
                new Object[]{Module.ADMIN_OPERATOR.getModule()}, (rs, rowNum) -> Demo.builder()
                        .rowNum(rowNum)
                        .operatedAt(rs.getTimestamp("operated_at").toLocalDateTime())
                        .operator(rs.getString("operator"))
                        .action(rs.getString("action"))
                        .name(rs.getString("name"))
                        .build()
        );

        return new PageImpl<>(demos, pageable, total);
    }
}

I agree with @Erica Kane for use of LIMIT and OFFSET.我同意@Erica Kane 使用 LIMIT 和 OFFSET。

However, If Database is not supporting LIMIT and OFFSET then you can use ROW_NUMBER()但是,如果数据库不支持 LIMIT 和 OFFSET 那么你可以使用 ROW_NUMBER()

for example -例如 -
SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY id) as RRN FROM user_addresses as T1 ) WHERE RRN between :start and :end; :start and :end you can give whatever number you wish to fetch result. :start 和 :end 你可以给出你想要获取结果的任何数字。 1 to 100 etc. 1 到 100 等
If Total rows are less than end number then it will simply return whatever rows present.如果总行数小于结束数,那么它将简单地返回任何存在的行。

Some of the best link I found regarding ROW_NUMBER() with great explanation-我发现的关于 ROW_NUMBER() 的一些最好的链接有很好的解释-

https://blog.sqlauthority.com/2011/08/12/sql-server-tips-from-the-sql-joes-2-pros-development-series-ranking-functions-rank-dense_rank-and-row_number-day-12-of-35/ https://blog.sqlauthority.com/2011/08/12/sql-server-tips-from-the-sql-joes-2-pros-development-series-ranking-functions-rank-dense_rank-and-row_number- 35 天 12 日/

https://blog.sqlauthority.com/2007/10/09/sql-server-2005-sample-example-of-ranking-functions-row_number-rank-dense_rank-ntile/ https://blog.sqlauthority.com/2007/10/09/sql-server-2005-sample-example-of-ranking-functions-row_number-rank-dense_rank-ntile/

https://blog.sqlauthority.com/2008/03/12/sql-server-2005-find-nth-highest-record-from-database-table-using-ranking-function-row_number/ https://blog.sqlauthority.com/2008/03/12/sql-server-2005-find-nth-highest-record-from-database-table-using-ranking-function-row_number/

https://blog.sqlauthority.com/2015/09/03/sql-server-whats-the-difference-between-row_number-rank-and-dense_rank-notes-from-the-field-096/ https://blog.sqlauthority.com/2015/09/03/sql-server-whats-the-difference-between-row_number-rank-and-dense_rank-notes-from-the-field-096/

I came across this while I was searching for something else, and noticed this has not been answered, so thought to post my 2cents.我在寻找其他东西时遇到了这个问题,并注意到这个问题没有得到回答,所以想发布我的 2cents。 You can create a wrapper (Request) object containing Pagination object and pageId.您可以创建一个包含 Pagination 对象和 pageId 的包装器 (Request) 对象。

Request要求

  • Pagination pagination分页
  • int pageId (any business related data/ SQL parameter) int pageId(任何与业务相关的数据/SQL 参数)
  • ANY DOMAIN OBJECT任何域对象

Pagination分页

  • int start (Use to set OFFSET property in the SQL) int start(用于在 SQL 中设置 OFFSET 属性)
  • int size (Use to set the FETCH NEXT property in the SQL) int size(用于设置 SQL 中的 FETCH NEXT 属性)

You don't have to create own implementation logic for pagination.您不必为分页创建自己的实现逻辑。 Use Spring's PagedListHolder , it's suitable and configurable for pagination purposes.使用 Spring 的PagedListHolder ,它适用于分页目的且可配置。

Here you can see an example implementation: Spring Pagination Example .在这里您可以看到一个示例实现: Spring Pagination Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在spring jdbcTemplate中实现连接查询? - how to implement join query in spring jdbcTemplate? 如何配置Spring以显示JdbcTemplate执行的查询? - How can I configure Spring to show the query performed by JdbcTemplate? 我怎样才能得到一个 spring JdbcTemplate 到 read_uncommitted? - How can I get a spring JdbcTemplate to read_uncommitted? 如何在JDBCTemplate spring 4中打开数据库连接 - How can i make database connection open in JDBCTemplate spring 4 如何使用Spring和JDBCTemplate取消长时间运行的查询? - How can I cancel a long-running query using Spring and JDBCTemplate? 如何在Spring Boot中通过jdbcTemplate将单个事务与多个数据源一起使用? - How can I use single transaction with multiple datasources with jdbcTemplate in spring boot? 如何在Swing桌面应用程序中使用Spring JDBC中的JDBCTemplate? - How can I use JDBCTemplate from Spring JDBC in a Swing desktop application? 如何使用 Hibernate 在 Spring Boot 中实现分页 - How to implement pagination in spring boot with hibernate Spring JdbcTemplate可以等待oracle存储过程完成多长时间 - how long can Spring JdbcTemplate wait for an oracle stored procedure to finish 如何在Spring JDBCTemplate中为数据源设置区分大小写``关闭&#39;&#39; - How do i set case sensitivity 'off' for a Datasource in spring jdbctemplate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM