1.在连接数据库时候,mysql是否支持fetchsize分页获取?
满足以下几个条件,可以使用fetchsize,根据游标获得记录
①MySQL 从5.0.2开始支持分页获得.
②同时需要在jdbc连接参数上配置 jdbc:mysql://localhost:3306/test?useCursorFetch=true
③设置FetchSize,在mybatis的 具体查询语句中配置 。<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap" fetchSize="5">
④isBinaryEncoded 如果是使用PreparedStatement则这个值为true
⑤如果使用PreparedStatement,则会生成JDBC42ServerPreparedStatement对象,在访问数据库时,会自动设置resultsetType=ResultSet.TYPE_FORWARD_ONLY
疑问:mybatis什么情况下会将statement的类型初始化为PreParedStatement?
在sql配置文件中有一个参数,statementType 可以自己设置。要不即使参数使用${}。也还是会使用PreparedStatement。默认是PreparedStatement
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap" fetchSize="5" statementType="PREPARED">
在MySQL的JDBC源码中:MysqlIO中
1 //版本>=5.0.2 && 连接上配置useCurSorFetch=true &&isBinaryEncoded =true &&
if (this.connection.versionMeetsMinimum(5, 0, 2) && this.connection.getUseCursorFetch() && isBinaryEncoded && callingStatement != null 2 && callingStatement.getFetchSize() != 0 && callingStatement.getResultSetType() == ResultSet.TYPE_FORWARD_ONLY) { 3 ServerPreparedStatement prepStmt = (com.mysql.jdbc.ServerPreparedStatement) callingStatement; 4 5 boolean usingCursor = true; 6 7 // 8 // Server versions 5.0.5 or newer will only open a cursor and set this flag if they can, otherwise they punt and go back to mysql_store_results() 9 // behavior 10 // 11 12 if (this.connection.versionMeetsMinimum(5, 0, 5)) { 13 usingCursor = (this.serverStatus & SERVER_STATUS_CURSOR_EXISTS) != 0; 14 } 15 16 if (usingCursor) { 17 RowData rows = new RowDataCursor(this, prepStmt, fields); 18 19 ResultSetImpl rs = buildResultSetWithRows(callingStatement, catalog, fields, rows, resultSetType, resultSetConcurrency, isBinaryEncoded); 20 21 if (usingCursor) { 22 rs.setFetchSize(callingStatement.getFetchSize()); 23 } 24 25 return rs; 26 } 27 }
2.Mybatis开启Mapper级别的缓存时,注意Bean需要继承Serializer接口