2016-12-24 85 views
1

我在理解JDBC中的分頁問題時遇到了問題,我希望能夠告訴我一些關於它的事情,我是java編程中的新手,並且不容易將這些方法的功能理解爲示例setFetchsize(); getFetchSize();我試圖在Mysql中關於用戶做一個表格,然後通過使用這個語句「SELECT * FROM User」從表格中獲取所有信息來進行分頁,我認爲我會得到前10行,然後是10,因爲它的默認值,我必須從數據庫中獲得所有的信息,這裏是我的代碼,我嘗試使用LIMIT,但我仍然不明白它的工作原理。使用JDBC分頁JAVA

@Override 
public List<User> getAll() throws SQLException { 

    try (PreparedStatement statement = connection.getConnection() 
      .prepareStatement("SELECT * FROM User")) { 

     int fetchSize = statement.getFetchSize(); 

     System.out.println("Statement fetch size : " + fetchSize); 

     statement.setFetchSize(50); 

     ResultSet result = statement.executeQuery(); 
     result.setFetchSize(33); 
     while (result.next()) { 
      list.add(extractUser(result)); 

     } 

    } catch (SQLException e) { 

     throw new RuntimeException(e); 
    } 
    System.out.println(list); 
    return list; 

} 

private User extractUser(ResultSet result) throws SQLException { 

    long id = result.getLong(1); 
    String userName = result.getString(2); 
    String firstName = result.getString(3); 
    String lastName = result.getString(4); 
    long teamId = result.getLong(5); 
    String userStatus = result.getString(6); 

    return new User(id, userName, firstName, lastName, teamId, userStatus); 

} 

回答

2

當JDBC需要從數據庫中提取一條記錄時,它會在其周圍獲取一批記錄以提高性能。該批量的大小可以使用setFetchSize進行控制。然而,這對查詢的結果有沒有功能影響。無論提取大小如何,您仍然會得到相同的結果。唯一會改變的是程序在每次訪問時獲取的記錄數(以及因此需要執行的提取次數)。

如果你想介紹分頁到你的應用程序,你需要自己編寫代碼,與limit子句:

public List<User> getAll(int beginIndex, int pageSize) throws SQLException { 

    try (PreparedStatement statement = 
      connection.getConnection().prepareStatement 
      ("SELECT * FROM User ORDER BY Username LIMIT ? OFFSET ?")) { 

     statement.setInt(1, pageSize); 
     statement.setInt(2, begineIndex); 

     ResultSet result = statement.executeQuery(); 
     while (result.next()) { 
      list.add(extractUser(result)); 
     } 
    } catch (SQLException e) { 
     throw new RuntimeException(e); 
    } 
    return list; 
}