在MyBatis中實現分頁查詢并返回總記錄數,可以通過在SQL語句中使用LIMIT關鍵字進行分頁,同時使用COUNT函數統計總記錄數。
以下是一個示例代碼:
List<User> getUserListByPage(Map<String, Object> params);
<select id="getUserListByPage" resultType="User">
select * from user
<where>
<!-- 這里可以添加條件參數 -->
</where>
limit #{start}, #{pageSize}
</select>
<select id="getUserCount" resultType="int">
select count(*) from user
<where>
<!-- 這里可以添加條件參數 -->
</where>
</select>
int getUserCount(Map<String, Object> params);
List<User> getUserListByPage(Map<String, Object> params) {
List<User> userList = sqlSession.selectList("getUserListByPage", params);
int totalCount = sqlSession.selectOne("getUserCount", params);
// 將總記錄數設置到參數中
params.put("totalCount", totalCount);
return userList;
}
Map<String, Object> params = new HashMap<>();
params.put("start", 0);
params.put("pageSize", 10);
List<User> userList = userService.getUserListByPage(params);
int totalCount = (int) params.get("totalCount");
通過以上步驟,可以實現在MyBatis中進行分頁查詢并返回總記錄數。