動態sql和分頁
阿新 • • 發佈:2018-12-30
1.mybatis動態sql
1.1 if
1.2 trim
1.3 foreach
1.4 其他
choose/set/where
2.模糊查詢(3種方式)
2.1 引數中直接加入%% 2.2 使用${...}代替#{...}(不建議使用該方式,有SQL注入風險) 關鍵:#{...}與${...}區別? 引數型別為字串,#會在前後加單引號['],$則直接插入值 注: 1) mybatis中使用OGNL表示式傳遞引數 2) 優先使用#{...} 3) ${...}方式存在SQL注入風險 2.3 SQL字串拼接CONCAT
3.查詢返回結果集
resultMap:適合使用返回值是自定義實體類的情況
resultType:適合使用返回值的資料型別是非自定義的,即jdk的提供的型別
3.1 使用resultMap返回自定義型別集合
3.2 使用resultType返回List<T>
3.3 使用resultType返回單個物件
3.4 使用resultType返回List<Map>,適用於多表查詢返回結果集
3.5 使用resultType返回Map<String,Object>,適用於多表查詢返回單個結果集
4.分頁查詢
為什麼要重寫mybatis的分頁?
Mybatis的分頁功能很弱,它是基於記憶體的分頁(查出所有記錄再按偏移量offset和邊界limit取結果),在大資料量的情況下這樣的分頁基本上是沒有用的
4.1 匯入分頁外掛 <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> 4.2 將pagehelper外掛配置到mybatis中 <!-- 配置分頁外掛PageHelper, 4.0.0以後的版本支援自動識別使用的資料庫 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> </plugin> 4.3 在你需要進行分頁的Mybatis方法前呼叫PageHelper.startPage靜態方法即可,緊跟在這個方法後的第一個Mybatis查詢方法會被進行分頁 //設定分頁處理 if (null != pageBean && pageBean.isPaginate()) { PageHelper.startPage(pageBean.getCurPage(), pageBean.getPageRecord()); } 4.4 獲取分頁資訊(二種方式) 4.4.1 使用外掛後,查詢實際返回的是Page<E>,而非List<E>,Page繼承了ArrayList,同時還包含分頁相關的資訊 Page<Book> page = (Page<Book>)list; System.out.println("頁碼:" + page.getPageNum()); System.out.println("頁大小:" + page.getPageSize()); System.out.println("總記錄:" + page.getTotal()); 4.4.2 使用PageInfo PageInfo pageInfo = new PageInfo(list); System.out.println("頁碼:" + pageInfo.getPageNum()); System.out.println("頁大小:" + pageInfo.getPageSize()); System.out.println("總記錄:" + pageInfo.getTotal());
5.特殊字元處理
>(>)
<(<)
&(&)
空格( )