ibatis實現分頁查詢
阿新 • • 發佈:2019-01-10
最近在做老專案改造,分享一個之前寫的ibatis(這裡特指ibatis3.0之前的版本)分頁外掛。
其實也算不上外掛,因為這個已經是hack-in的寫法。大致原理就是替換ibatis的SqlExecutor,然後通過重寫executeQuery方法,對分頁做特殊處理。
程式碼是基於ibatis-sqlmap-2.3.4.726-sources寫的(https://git.coding.net/lichmama/ibatis-pagination.git)核心檔案就5個:
使用起來也很簡單,給個結合spring的例子來看:
sqlmap檔案:
<sqlMap namespace="userDAO"> <!-- 省略其他配置... --> <select id="getUsersByParam" parameterClass="map" resultMap="UserMap"> select * from users <dynamic prepend="where"> <isNotEmpty prepend="and" property="gender"> gender = #gender#</isNotEmpty> <isNotEmpty prepend="and" property="status"> status = #status# </isNotEmpty> <isNotEmpty prepend="and" property="username"> username like concat('%', #gender#, '%') </isNotEmpty> </dynamic> order by id asc </select> </sqlMap>
IBatisBaseDao.java:
public abstract class IBatisBaseDAO<E, K> extends SqlMapClientDaoSupport { private static PagedSqlExecutor pagedSqlExecutor; @Override protected void initDao() throws Exception { super.initDao(); synchronized (IBatisBaseDAO.class) { if (pagedSqlExecutor == null) { synchronized (IBatisBaseDAO.class) { pagedSqlExecutor = SpringContextHolder.getBean(PagedSqlExecutor.class); ((SqlMapClientImpl) getSqlMapClient()).getDelegate().setSqlExecutor(pagedSqlExecutor); } } } } public abstract String getNamespace(); public String getSqlId(String statementName) { return getNamespace() + "." + statementName; } public Page queryForPage(String statementName, Object paramObject, Page page) { try { List list = getSqlMapClient().queryForList(getSqlId(statementName), paramObject, page.getBeginPos(), page.getPageSize()); page.setTotalRows(pagedSqlExecutor.getRowsCount()); page.setResultList(list); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return page; } }
UserDAOImpl.java:
public class UserDAOImpl extends IBatisBaseDAO<User, Integer> implements IUserDAO { @Override public String getNamespace() { return "userDAO"; } // 呼叫queryForPage實現分頁查詢 public Page getUsersPaged(Map paramObject, int currentPage, int pageSize) { Page page = new Page(); page.setCurrentPage(currentPage); page.setPageSize(pageSize); return queryForPage("getUsersByParam", paramObject, page); } }
關鍵spring配置:
<bean id="pagedSqlExecutor" class="com.ibatis.pagination.PagedSqlExecutor"> <property name="pagination"> <!-- 跟資料庫型別選擇:mysql/oracle --> <bean class="com.ibatis.pagination.impl.MySQLPagination" /> </property> </bean> <bean id="userDAO" class="com.lichmama.dao.impl.UserDAOImpl"> <property name="sqlMapClient" ref="sqlMapClient" /> </bean>