Ibatis SqlExecutor.executeQuery(ZZ)

标签: ibatissqlparametersstringcallback数据库

 

分类: Java(23) 

[Java]      view plain      copy     
     
   
1. 一直以来ibatis的分页都是通过滚动ResultSet实现的,应该算是逻辑分页吧。逻辑分页虽然能很干净地独立于特定数据库,但效率在多数情况下不及特定数据库支持的物理分页,而hibernate的分页则是直接组装sql,充分利用了特定数据库的分页机制,效率相对较高。本文讲述的就是如何在不重新编译ibatis源码的前提下,为ibatis引入hibernate式的物理分页机制。  
2.   
3. 基本思路就是找到ibatis执行sql的地方,截获sql并重新组装sql。通过分析ibatis源码知道,最终负责执行sql的类是com.ibatis.sqlmap.engine.execution.SqlExecutor,此类没有实现任何接口,这多少有点遗憾,因为接口是相对稳定契约,非大的版本更新,接口一般是不会变的,而类就相对易变一些,所以这里的代码只能保证对当前版本(2.1.7)的ibatis有效。下面是SqlExecutor执行查询的方法:  
4.   
5. /**
6.    * Long form of the method to execute a query
7.    *
8.    * @param request - the request scope
9.    * @param conn - the database connection
10.    * @param sql - the SQL statement to execute
11.    * @param parameters - the parameters for the statement
12.    * @param skipResults - the number of results to skip
13.    * @param maxResults - the maximum number of results to return
14.    * @param callback - the row handler for the query
15.    *
16.    * @throws SQLException - if the query fails
17.    */  
18. public void executeQuery(RequestScope request, Connection conn, String sql, Object[] parameters,  
19. int skipResults, int maxResults, RowHandlerCallback callback)  
20. throws SQLException {  
21.     ErrorContext errorContext = request.getErrorContext();  
22. "executing query");  
23.     errorContext.setObjectId(sql);  
24.   
25. null;  
26. null;  
27.   
28. try {  
29. "Check the SQL Statement (preparation failed).");  
30.   
31.       Integer rsType = request.getStatement().getResultSetType();  
32. if (rsType != null) {  
33.         ps = conn.prepareStatement(sql, rsType.intValue(), ResultSet.CONCUR_READ_ONLY);  
34. else {  
35.         ps = conn.prepareStatement(sql);  
36.       }  
37.   
38.       Integer fetchSize = request.getStatement().getFetchSize();  
39. if (fetchSize != null) {  
40.         ps.setFetchSize(fetchSize.intValue());  
41.       }  
42.   
43. "Check the parameters (set parameters failed).");  
44.       request.getParameterMap().setParameters(request, ps, parameters);  
45.   
46. "Check the statement (query failed).");  
47.   
48.       ps.execute();  
49.       rs = getFirstResultSet(ps);  
50.   
51. if (rs != null) {  
52. "Check the results (failed to retrieve results).");  
53.         handleResults(request, rs, skipResults, maxResults, callback);  
54.       }  
55.   
56. // clear out remaining results  
57. while (ps.getMoreResults());  
58.   
59. finally {  
60. try {  
61.         closeResultSet(rs);  
62. finally {  
63.         closeStatement(ps);  
64.       }  
65.     }  
66.   
67.   }  
68.   
69. 其中handleResults(request, rs, skipResults, maxResults, callback)一句用于处理分页,其实此时查询已经执行完毕,可以不必关心handleResults方法,但为清楚起见,下面来看看handleResults的实现:  
70.   
71. private void handleResults(RequestScope request, ResultSet rs, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {  
72. try {  
73.       request.setResultSet(rs);  
74.       ResultMap resultMap = request.getResultMap();  
75. if (resultMap != null) {  
76. // Skip Results  
77. if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {  
78. if (skipResults > 0) {  
79.             rs.absolute(skipResults);  
80.           }  
81. else {  
82. for (int i = 0; i < skipResults; i++) {  
83. if (!rs.next()) {  
84. break;  
85.             }  
86.           }  
87.         }  
88.   
89. // Get Results  
90. int resultsFetched = 0;  
91. while ((maxResults == SqlExecutor.NO_MAXIMUM_RESULTS || resultsFetched < maxResults) && rs.next()) {  
92.           Object[] columnValues = resultMap.resolveSubMap(request, rs).getResults(request, rs);  
93.           callback.handleResultObject(request, columnValues, rs);  
94.           resultsFetched++;  
95.         }  
96.       }  
97. finally {  
98. null);  
99.     }  
100.   }  
101.   
102. 此处优先使用的是ResultSet的absolute方法定位记录,是否支持absolute取决于具体数据库驱动,但一般当前版本的数据库都支持该方法,如果不支持则逐条跳过前面的记录。由此可以看出如果数据库支持absolute,则ibatis内置的分页策略与特定数据库的物理分页效率差距就在于物理分页查询与不分页查询在数据库中的执行效率的差距了。因为查询执行后读取数据前数据库并未把结果全部返回到内存,所以本身在存储占用上应该差距不大,如果都使用索引,估计执行速度也差不太多。  
103.   
104. 继续我们的话题。其实只要在executeQuery执行前组装sql,然后将其传给executeQuery,并告诉handleResults我们不需要逻辑分页即可。拦截executeQuery可以采用aop动态实现,也可直接继承SqlExecutor覆盖executeQuery来静态地实现,相比之下后者要简单许多,而且由于SqlExecutor没有实现任何接口,比较易变,动态拦截反到增加了维护的工作量,所以我们下面来覆盖executeQuery:  
105.   
106. package com.aladdin.dao.ibatis.ext;  
107.   
108. import java.sql.Connection;  
109. import java.sql.SQLException;  
110.   
111. import org.apache.commons.logging.Log;  
112. import org.apache.commons.logging.LogFactory;  
113.   
114. import com.aladdin.dao.dialect.Dialect;  
115. import com.ibatis.sqlmap.engine.execution.SqlExecutor;  
116. import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;  
117. import com.ibatis.sqlmap.engine.scope.RequestScope;  
118.   
119. public class LimitSqlExecutor extends SqlExecutor {  
120.   
121. private static final Log logger = LogFactory.getLog(LimitSqlExecutor.class);  
122.       
123. private Dialect dialect;  
124.   
125. private boolean enableLimit = true;  
126.   
127. public Dialect getDialect() {  
128. return dialect;  
129.     }  
130.   
131. public void setDialect(Dialect dialect) {  
132. this.dialect = dialect;  
133.     }  
134.   
135. public boolean isEnableLimit() {  
136. return enableLimit;  
137.     }  
138.   
139. public void setEnableLimit(boolean enableLimit) {  
140. this.enableLimit = enableLimit;  
141.     }  
142.   
143. @Override  
144. public void executeQuery(RequestScope request, Connection conn, String sql,  
145. int skipResults, int maxResults,  
146. throws SQLException {  
147. if ((skipResults != NO_SKIPPED_RESULTS || maxResults != NO_MAXIMUM_RESULTS)  
148.                 && supportsLimit()) {  
149.             sql = dialect.getLimitString(sql, skipResults, maxResults);  
150. if(logger.isDebugEnabled()){  
151.                 logger.debug(sql);  
152.             }  
153.             skipResults = NO_SKIPPED_RESULTS;  
154.             maxResults = NO_MAXIMUM_RESULTS;              
155.         }  
156. super.executeQuery(request, conn, sql, parameters, skipResults,  
157.                 maxResults, callback);  
158.     }  
159.   
160. public boolean supportsLimit() {  
161. if (enableLimit && dialect != null) {  
162. return dialect.supportsLimit();  
163.         }  
164. return false;  
165.     }  
166.   
167. }  
168.   
169. 其中:  
170.   
171. skipResults = NO_SKIPPED_RESULTS;  
172. maxResults = NO_MAXIMUM_RESULTS;  
173.   
174. 告诉handleResults不分页(我们组装的sql已经使查询结果是分页后的结果了),此处引入了类似hibenate中的数据库方言接口Dialect,其代码如下:  
175.   
176. package com.aladdin.dao.dialect;  
177.   
178. public interface Dialect {  
179.       
180. public boolean supportsLimit();  
181.   
182. public String getLimitString(String sql, boolean hasOffset);  
183.   
184. public String getLimitString(String sql, int offset, int limit);  
185. }  
186.   
187.    
188.   
189. 下面为Dialect接口的MySQL实现:   
190.   
191. package com.aladdin.dao.dialect;  
192.   
193. public class MySQLDialect implements Dialect {  
194.   
195. protected static final String SQL_END_DELIMITER = ";";  
196.   
197. public String getLimitString(String sql, boolean hasOffset) {  
198. return new StringBuffer(sql.length() + 20).append(trim(sql)).append(  
199. " limit ?,?" : " limit ?")  
200.                 .append(SQL_END_DELIMITER).toString();  
201.     }  
202.   
203. public String getLimitString(String sql, int offset, int limit) {  
204.         sql = trim(sql);  
205. new StringBuffer(sql.length() + 20);  
206.         sb.append(sql);  
207. if (offset > 0) {  
208. " limit ").append(offset).append(',').append(limit)  
209.                     .append(SQL_END_DELIMITER);  
210. else {  
211. " limit ").append(limit).append(SQL_END_DELIMITER);  
212.         }  
213. return sb.toString();  
214.     }  
215.   
216. public boolean supportsLimit() {  
217. return true;  
218.     }  
219.   
220. private String trim(String sql) {  
221.         sql = sql.trim();  
222. if (sql.endsWith(SQL_END_DELIMITER)) {  
223. 0, sql.length() - 1  
224.                     - SQL_END_DELIMITER.length());  
225.         }  
226. return sql;  
227.     }  
228.   
229. }  
230.   
231. 接下来的工作就是把LimitSqlExecutor注入ibatis中。我们是通过spring来使用ibatis的,所以在我们的dao基类中执行注入,代码如下:  
232.   
233. package com.aladdin.dao.ibatis;  
234.   
235. import java.io.Serializable;  
236. import java.util.List;  
237.   
238. import org.springframework.orm.ObjectRetrievalFailureException;  
239. import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;  
240.   
241. import com.aladdin.dao.ibatis.ext.LimitSqlExecutor;  
242. import com.aladdin.domain.BaseObject;  
243. import com.aladdin.util.ReflectUtil;  
244. import com.ibatis.sqlmap.client.SqlMapClient;  
245. import com.ibatis.sqlmap.engine.execution.SqlExecutor;  
246. import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient;  
247.   
248. public abstract class BaseDaoiBatis extends SqlMapClientDaoSupport {  
249.   
250. private SqlExecutor sqlExecutor;  
251.   
252. public SqlExecutor getSqlExecutor() {  
253. return sqlExecutor;  
254.     }  
255.   
256. public void setSqlExecutor(SqlExecutor sqlExecutor) {  
257. this.sqlExecutor = sqlExecutor;  
258.     }  
259.   
260. public void setEnableLimit(boolean enableLimit) {  
261. if (sqlExecutor instanceof LimitSqlExecutor) {  
262.             ((LimitSqlExecutor) sqlExecutor).setEnableLimit(enableLimit);  
263.         }  
264.     }  
265.   
266. public void initialize() throws Exception {  
267. if (sqlExecutor != null) {  
268.             SqlMapClient sqlMapClient = getSqlMapClientTemplate()  
269.                     .getSqlMapClient();  
270. if (sqlMapClient instanceof ExtendedSqlMapClient) {  
271.                 ReflectUtil.setFieldValue(((ExtendedSqlMapClient) sqlMapClient)  
272. "sqlExecutor", SqlExecutor.class,  
273.                         sqlExecutor);  
274.             }  
275.         }  
276.     }  
277.   
278.     ...  
279.   
280. }  
281.   
282.    
283.   
284. 其中的initialize方法执行注入,稍后会看到此方法在spring Beans 配置中指定为init-method。由于sqlExecutor是com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient的私有成员,且没有公开的set方法,所以此处通过反射绕过java的访问控制,下面是ReflectUtil的实现代码:  
285.   
286. package com.aladdin.util;  
287.   
288. import java.lang.reflect.Field;  
289. import java.lang.reflect.Method;  
290. import java.lang.reflect.Modifier;  
291.   
292. import org.apache.commons.logging.Log;  
293. import org.apache.commons.logging.LogFactory;  
294.   
295. public class ReflectUtil {  
296.   
297. private static final Log logger = LogFactory.getLog(ReflectUtil.class);  
298.   
299. public static void setFieldValue(Object target, String fname, Class ftype,  
300.             Object fvalue) {  
301. if (target == null  
302. null  
303. "".equals(fname)  
304. null && !ftype.isAssignableFrom(fvalue.getClass()))) {  
305. return;  
306.         }  
307.         Class clazz = target.getClass();  
308. try {  
309. "set"  
310. 0))  
311. 1), ftype);  
312. if (!Modifier.isPublic(method.getModifiers())) {  
313. true);  
314.             }  
315.             method.invoke(target, fvalue);  
316.   
317. catch (Exception me) {  
318. if (logger.isDebugEnabled()) {  
319.                 logger.debug(me);  
320.             }  
321. try {  
322.                 Field field = clazz.getDeclaredField(fname);  
323. if (!Modifier.isPublic(field.getModifiers())) {  
324. true);  
325.                 }  
326.                 field.set(target, fvalue);  
327. catch (Exception fe) {  
328. if (logger.isDebugEnabled()) {  
329.                     logger.debug(fe);  
330.                 }  
331.             }  
332.         }  
333.     }  
334. }<pre></pre>  
  
 
  
     [XML]      view plain      copy     
     
   
1. 到此剩下的就是通过Spring将sqlExecutor注入BaseDaoiBatis中了,下面是Spring Beans配置文件:  
2.   
3. <!--?xml version="1.0" encoding="UTF-8"?-->  
4.   
5.   
6. <beans>  
7. <!-- Transaction manager for a single JDBC DataSource -->  
8. <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">  
9. <property name="dataSource">  
10. <ref bean="dataSource">  
11. </ref></property>  
12. </bean>  
13.       
14. <!-- SqlMap setup for iBATIS Database Layer -->  
15. <bean class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" id="sqlMapClient">  
16. <property name="configLocation">  
17. <value>classpath:/com/aladdin/dao/ibatis/sql-map-config.xml</value>  
18. </property>  
19. <property name="dataSource">  
20. <ref bean="dataSource">  
21. </ref></property>  
22. </bean>  
23.   
24. <bean class="com.aladdin.dao.ibatis.ext.LimitSqlExecutor" id="sqlExecutor">  
25. <property name="dialect">  
26. <bean class="com.aladdin.dao.dialect.MySQLDialect">  
27. </bean></property>  
28. </bean>  
29.       
30. <bean class="com.aladdin.dao.ibatis.BaseDaoiBatis" id="baseDao" init-method="initialize" abstract="true">  
31. <property name="dataSource">  
32. <ref bean="dataSource">  
33. </ref></property>  
34. <property name="sqlMapClient">  
35. <ref bean="sqlMapClient">  
36. </ref></property>  
37. <property name="sqlExecutor">  
38. <ref bean="sqlExecutor">  
39. </ref></property>   
40. </bean>   
41.       
42. <bean class="com.aladdin.dao.ibatis.UserDaoiBatis" id="userDao" parent="baseDao">   
43.   
44. <bean class="com.aladdin.dao.ibatis.RoleDaoiBatis" id="roleDao" parent="baseDao">  
45.       
46. <bean class="com.aladdin.dao.ibatis.ResourceDaoiBatis" id="resourceDao" parent="baseDao">     
47. </bean></bean></bean></beans><pre></pre>  
  
 
  
     [Java]      view plain      copy     
     
   
1. 此后就可以通过调用org.springframework.orm.ibatis.SqlMapClientTemplate的  
2. public List queryForList(final String statementName, final Object parameterObject, final int skipResults, final int maxResults)   throws DataAccessException  
3. 或  
4. public PaginatedList queryForPaginatedList(final String statementName, final Object parameterObject, final int pageSize)   throws DataAccessException   
5.   
6. 得到分页结果了。建议使用第一个方法,第二个方法返回的是PaginatedList,虽然使用简单,但是其获得指定页的数据是跨过我们的dao直接访问ibatis的,不方便统一管理。   
7. <pre></pre>  
  
 
         
 
 
  
     [Java]      view plain      copy     
     
   
1. 一直以来ibatis的分页都是通过滚动ResultSet实现的,应该算是逻辑分页吧。逻辑分页虽然能很干净地独立于特定数据库,但效率在多数情况下不及特定数据库支持的物理分页,而hibernate的分页则是直接组装sql,充分利用了特定数据库的分页机制,效率相对较高。本文讲述的就是如何在不重新编译ibatis源码的前提下,为ibatis引入hibernate式的物理分页机制。  
2.   
3. 基本思路就是找到ibatis执行sql的地方,截获sql并重新组装sql。通过分析ibatis源码知道,最终负责执行sql的类是com.ibatis.sqlmap.engine.execution.SqlExecutor,此类没有实现任何接口,这多少有点遗憾,因为接口是相对稳定契约,非大的版本更新,接口一般是不会变的,而类就相对易变一些,所以这里的代码只能保证对当前版本(2.1.7)的ibatis有效。下面是SqlExecutor执行查询的方法:  
4.   
5. /**
6.    * Long form of the method to execute a query
7.    *
8.    * @param request - the request scope
9.    * @param conn - the database connection
10.    * @param sql - the SQL statement to execute
11.    * @param parameters - the parameters for the statement
12.    * @param skipResults - the number of results to skip
13.    * @param maxResults - the maximum number of results to return
14.    * @param callback - the row handler for the query
15.    *
16.    * @throws SQLException - if the query fails
17.    */  
18. public void executeQuery(RequestScope request, Connection conn, String sql, Object[] parameters,  
19. int skipResults, int maxResults, RowHandlerCallback callback)  
20. throws SQLException {  
21.     ErrorContext errorContext = request.getErrorContext();  
22. "executing query");  
23.     errorContext.setObjectId(sql);  
24.   
25. null;  
26. null;  
27.   
28. try {  
29. "Check the SQL Statement (preparation failed).");  
30.   
31.       Integer rsType = request.getStatement().getResultSetType();  
32. if (rsType != null) {  
33.         ps = conn.prepareStatement(sql, rsType.intValue(), ResultSet.CONCUR_READ_ONLY);  
34. else {  
35.         ps = conn.prepareStatement(sql);  
36.       }  
37.   
38.       Integer fetchSize = request.getStatement().getFetchSize();  
39. if (fetchSize != null) {  
40.         ps.setFetchSize(fetchSize.intValue());  
41.       }  
42.   
43. "Check the parameters (set parameters failed).");  
44.       request.getParameterMap().setParameters(request, ps, parameters);  
45.   
46. "Check the statement (query failed).");  
47.   
48.       ps.execute();  
49.       rs = getFirstResultSet(ps);  
50.   
51. if (rs != null) {  
52. "Check the results (failed to retrieve results).");  
53.         handleResults(request, rs, skipResults, maxResults, callback);  
54.       }  
55.   
56. // clear out remaining results  
57. while (ps.getMoreResults());  
58.   
59. finally {  
60. try {  
61.         closeResultSet(rs);  
62. finally {  
63.         closeStatement(ps);  
64.       }  
65.     }  
66.   
67.   }  
68.   
69. 其中handleResults(request, rs, skipResults, maxResults, callback)一句用于处理分页,其实此时查询已经执行完毕,可以不必关心handleResults方法,但为清楚起见,下面来看看handleResults的实现:  
70.   
71. private void handleResults(RequestScope request, ResultSet rs, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {  
72. try {  
73.       request.setResultSet(rs);  
74.       ResultMap resultMap = request.getResultMap();  
75. if (resultMap != null) {  
76. // Skip Results  
77. if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {  
78. if (skipResults > 0) {  
79.             rs.absolute(skipResults);  
80.           }  
81. else {  
82. for (int i = 0; i < skipResults; i++) {  
83. if (!rs.next()) {  
84. break;  
85.             }  
86.           }  
87.         }  
88.   
89. // Get Results  
90. int resultsFetched = 0;  
91. while ((maxResults == SqlExecutor.NO_MAXIMUM_RESULTS || resultsFetched < maxResults) && rs.next()) {  
92.           Object[] columnValues = resultMap.resolveSubMap(request, rs).getResults(request, rs);  
93.           callback.handleResultObject(request, columnValues, rs);  
94.           resultsFetched++;  
95.         }  
96.       }  
97. finally {  
98. null);  
99.     }  
100.   }  
101.   
102. 此处优先使用的是ResultSet的absolute方法定位记录,是否支持absolute取决于具体数据库驱动,但一般当前版本的数据库都支持该方法,如果不支持则逐条跳过前面的记录。由此可以看出如果数据库支持absolute,则ibatis内置的分页策略与特定数据库的物理分页效率差距就在于物理分页查询与不分页查询在数据库中的执行效率的差距了。因为查询执行后读取数据前数据库并未把结果全部返回到内存,所以本身在存储占用上应该差距不大,如果都使用索引,估计执行速度也差不太多。  
103.   
104. 继续我们的话题。其实只要在executeQuery执行前组装sql,然后将其传给executeQuery,并告诉handleResults我们不需要逻辑分页即可。拦截executeQuery可以采用aop动态实现,也可直接继承SqlExecutor覆盖executeQuery来静态地实现,相比之下后者要简单许多,而且由于SqlExecutor没有实现任何接口,比较易变,动态拦截反到增加了维护的工作量,所以我们下面来覆盖executeQuery:  
105.   
106. package com.aladdin.dao.ibatis.ext;  
107.   
108. import java.sql.Connection;  
109. import java.sql.SQLException;  
110.   
111. import org.apache.commons.logging.Log;  
112. import org.apache.commons.logging.LogFactory;  
113.   
114. import com.aladdin.dao.dialect.Dialect;  
115. import com.ibatis.sqlmap.engine.execution.SqlExecutor;  
116. import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;  
117. import com.ibatis.sqlmap.engine.scope.RequestScope;  
118.   
119. public class LimitSqlExecutor extends SqlExecutor {  
120.   
121. private static final Log logger = LogFactory.getLog(LimitSqlExecutor.class);  
122.       
123. private Dialect dialect;  
124.   
125. private boolean enableLimit = true;  
126.   
127. public Dialect getDialect() {  
128. return dialect;  
129.     }  
130.   
131. public void setDialect(Dialect dialect) {  
132. this.dialect = dialect;  
133.     }  
134.   
135. public boolean isEnableLimit() {  
136. return enableLimit;  
137.     }  
138.   
139. public void setEnableLimit(boolean enableLimit) {  
140. this.enableLimit = enableLimit;  
141.     }  
142.   
143. @Override  
144. public void executeQuery(RequestScope request, Connection conn, String sql,  
145. int skipResults, int maxResults,  
146. throws SQLException {  
147. if ((skipResults != NO_SKIPPED_RESULTS || maxResults != NO_MAXIMUM_RESULTS)  
148.                 && supportsLimit()) {  
149.             sql = dialect.getLimitString(sql, skipResults, maxResults);  
150. if(logger.isDebugEnabled()){  
151.                 logger.debug(sql);  
152.             }  
153.             skipResults = NO_SKIPPED_RESULTS;  
154.             maxResults = NO_MAXIMUM_RESULTS;              
155.         }  
156. super.executeQuery(request, conn, sql, parameters, skipResults,  
157.                 maxResults, callback);  
158.     }  
159.   
160. public boolean supportsLimit() {  
161. if (enableLimit && dialect != null) {  
162. return dialect.supportsLimit();  
163.         }  
164. return false;  
165.     }  
166.   
167. }  
168.   
169. 其中:  
170.   
171. skipResults = NO_SKIPPED_RESULTS;  
172. maxResults = NO_MAXIMUM_RESULTS;  
173.   
174. 告诉handleResults不分页(我们组装的sql已经使查询结果是分页后的结果了),此处引入了类似hibenate中的数据库方言接口Dialect,其代码如下:  
175.   
176. package com.aladdin.dao.dialect;  
177.   
178. public interface Dialect {  
179.       
180. public boolean supportsLimit();  
181.   
182. public String getLimitString(String sql, boolean hasOffset);  
183.   
184. public String getLimitString(String sql, int offset, int limit);  
185. }  
186.   
187.    
188.   
189. 下面为Dialect接口的MySQL实现:   
190.   
191. package com.aladdin.dao.dialect;  
192.   
193. public class MySQLDialect implements Dialect {  
194.   
195. protected static final String SQL_END_DELIMITER = ";";  
196.   
197. public String getLimitString(String sql, boolean hasOffset) {  
198. return new StringBuffer(sql.length() + 20).append(trim(sql)).append(  
199. " limit ?,?" : " limit ?")  
200.                 .append(SQL_END_DELIMITER).toString();  
201.     }  
202.   
203. public String getLimitString(String sql, int offset, int limit) {  
204.         sql = trim(sql);  
205. new StringBuffer(sql.length() + 20);  
206.         sb.append(sql);  
207. if (offset > 0) {  
208. " limit ").append(offset).append(',').append(limit)  
209.                     .append(SQL_END_DELIMITER);  
210. else {  
211. " limit ").append(limit).append(SQL_END_DELIMITER);  
212.         }  
213. return sb.toString();  
214.     }  
215.   
216. public boolean supportsLimit() {  
217. return true;  
218.     }  
219.   
220. private String trim(String sql) {  
221.         sql = sql.trim();  
222. if (sql.endsWith(SQL_END_DELIMITER)) {  
223. 0, sql.length() - 1  
224.                     - SQL_END_DELIMITER.length());  
225.         }  
226. return sql;  
227.     }  
228.   
229. }  
230.   
231. 接下来的工作就是把LimitSqlExecutor注入ibatis中。我们是通过spring来使用ibatis的,所以在我们的dao基类中执行注入,代码如下:  
232.   
233. package com.aladdin.dao.ibatis;  
234.   
235. import java.io.Serializable;  
236. import java.util.List;  
237.   
238. import org.springframework.orm.ObjectRetrievalFailureException;  
239. import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;  
240.   
241. import com.aladdin.dao.ibatis.ext.LimitSqlExecutor;  
242. import com.aladdin.domain.BaseObject;  
243. import com.aladdin.util.ReflectUtil;  
244. import com.ibatis.sqlmap.client.SqlMapClient;  
245. import com.ibatis.sqlmap.engine.execution.SqlExecutor;  
246. import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient;  
247.   
248. public abstract class BaseDaoiBatis extends SqlMapClientDaoSupport {  
249.   
250. private SqlExecutor sqlExecutor;  
251.   
252. public SqlExecutor getSqlExecutor() {  
253. return sqlExecutor;  
254.     }  
255.   
256. public void setSqlExecutor(SqlExecutor sqlExecutor) {  
257. this.sqlExecutor = sqlExecutor;  
258.     }  
259.   
260. public void setEnableLimit(boolean enableLimit) {  
261. if (sqlExecutor instanceof LimitSqlExecutor) {  
262.             ((LimitSqlExecutor) sqlExecutor).setEnableLimit(enableLimit);  
263.         }  
264.     }  
265.   
266. public void initialize() throws Exception {  
267. if (sqlExecutor != null) {  
268.             SqlMapClient sqlMapClient = getSqlMapClientTemplate()  
269.                     .getSqlMapClient();  
270. if (sqlMapClient instanceof ExtendedSqlMapClient) {  
271.                 ReflectUtil.setFieldValue(((ExtendedSqlMapClient) sqlMapClient)  
272. "sqlExecutor", SqlExecutor.class,  
273.                         sqlExecutor);  
274.             }  
275.         }  
276.     }  
277.   
278.     ...  
279.   
280. }  
281.   
282.    
283.   
284. 其中的initialize方法执行注入,稍后会看到此方法在spring Beans 配置中指定为init-method。由于sqlExecutor是com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient的私有成员,且没有公开的set方法,所以此处通过反射绕过java的访问控制,下面是ReflectUtil的实现代码:  
285.   
286. package com.aladdin.util;  
287.   
288. import java.lang.reflect.Field;  
289. import java.lang.reflect.Method;  
290. import java.lang.reflect.Modifier;  
291.   
292. import org.apache.commons.logging.Log;  
293. import org.apache.commons.logging.LogFactory;  
294.   
295. public class ReflectUtil {  
296.   
297. private static final Log logger = LogFactory.getLog(ReflectUtil.class);  
298.   
299. public static void setFieldValue(Object target, String fname, Class ftype,  
300.             Object fvalue) {  
301. if (target == null  
302. null  
303. "".equals(fname)  
304. null && !ftype.isAssignableFrom(fvalue.getClass()))) {  
305. return;  
306.         }  
307.         Class clazz = target.getClass();  
308. try {  
309. "set"  
310. 0))  
311. 1), ftype);  
312. if (!Modifier.isPublic(method.getModifiers())) {  
313. true);  
314.             }  
315.             method.invoke(target, fvalue);  
316.   
317. catch (Exception me) {  
318. if (logger.isDebugEnabled()) {  
319.                 logger.debug(me);  
320.             }  
321. try {  
322.                 Field field = clazz.getDeclaredField(fname);  
323. if (!Modifier.isPublic(field.getModifiers())) {  
324. true);  
325.                 }  
326.                 field.set(target, fvalue);  
327. catch (Exception fe) {  
328. if (logger.isDebugEnabled()) {  
329.                     logger.debug(fe);  
330.                 }  
331.             }  
332.         }  
333.     }  
334. }<pre></pre>  
  
 
  
     [XML]      view plain      copy     
     
   
1. 到此剩下的就是通过Spring将sqlExecutor注入BaseDaoiBatis中了,下面是Spring Beans配置文件:  
2.   
3. <!--?xml version="1.0" encoding="UTF-8"?-->  
4.   
5.   
6. <beans>  
7. <!-- Transaction manager for a single JDBC DataSource -->  
8. <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">  
9. <property name="dataSource">  
10. <ref bean="dataSource">  
11. </ref></property>  
12. </bean>  
13.       
14. <!-- SqlMap setup for iBATIS Database Layer -->  
15. <bean class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" id="sqlMapClient">  
16. <property name="configLocation">  
17. <value>classpath:/com/aladdin/dao/ibatis/sql-map-config.xml</value>  
18. </property>  
19. <property name="dataSource">  
20. <ref bean="dataSource">  
21. </ref></property>  
22. </bean>  
23.   
24. <bean class="com.aladdin.dao.ibatis.ext.LimitSqlExecutor" id="sqlExecutor">  
25. <property name="dialect">  
26. <bean class="com.aladdin.dao.dialect.MySQLDialect">  
27. </bean></property>  
28. </bean>  
29.       
30. <bean class="com.aladdin.dao.ibatis.BaseDaoiBatis" id="baseDao" init-method="initialize" abstract="true">  
31. <property name="dataSource">  
32. <ref bean="dataSource">  
33. </ref></property>  
34. <property name="sqlMapClient">  
35. <ref bean="sqlMapClient">  
36. </ref></property>  
37. <property name="sqlExecutor">  
38. <ref bean="sqlExecutor">  
39. </ref></property>   
40. </bean>   
41.       
42. <bean class="com.aladdin.dao.ibatis.UserDaoiBatis" id="userDao" parent="baseDao">   
43.   
44. <bean class="com.aladdin.dao.ibatis.RoleDaoiBatis" id="roleDao" parent="baseDao">  
45.       
46. <bean class="com.aladdin.dao.ibatis.ResourceDaoiBatis" id="resourceDao" parent="baseDao">     
47. </bean></bean></bean></beans><pre></pre>  
  
 
  
     [Java]      view plain      copy     
     
   
1. 此后就可以通过调用org.springframework.orm.ibatis.SqlMapClientTemplate的  
2. public List queryForList(final String statementName, final Object parameterObject, final int skipResults, final int maxResults)   throws DataAccessException  
3. 或  
4. public PaginatedList queryForPaginatedList(final String statementName, final Object parameterObject, final int pageSize)   throws DataAccessException   
5.   
6. 得到分页结果了。建议使用第一个方法,第二个方法返回的是PaginatedList,虽然使用简单,但是其获得指定页的数据是跨过我们的dao直接访问ibatis的,不方便统一管理。   
7. <pre></pre>