1、mybatis動態sql
2、模糊查詢
3、查詢返回結果集的處理
4、分頁查詢
5、特殊字符處理
1.mybatis動態sql
If、trim、foreach
If 標簽判斷某一字段是否為空
<select id="list4" resultType="java.util.Map" parameterType="java.util.Map"> select * from t_mvc_book <where> <if test="null != bname and bname !=''"> and bname like #{bname} </if> </where> </select>
trim 標簽一般用於去除sql語句中多余的and關鍵字,逗號,或者給sql語句前拼接 “where“、“set“以及“values(“ 等前綴,或者添加“)“等后綴,可用於選擇性插入、更新、刪除或者條件查詢等操作。
<trim prefix="values (" suffix=")" suffixOverrides="," > <if test="bid != null" > #{bid,jdbcType=INTEGER}, </if> <if test="bname != null" > #{bname,jdbcType=VARCHAR}, </if> <if test="price != null" > #{price,jdbcType=DOUBLE}, </if> </trim>
foreach 標簽 遍歷集合,批量查詢、通常用於in關鍵字
<select id="selectByIn" resultType="com.liuwenwu.model.Book" parameterType="java.util.List"> select * from t_mvc_book where bid in <foreach collection="bookIds" open="(" close=")" separator="," item="bid"> #{bid} </foreach> </select>
List<Book> selectByIn(@Param("bookIds")List bookIds);
測試
@Test public void selectByIn() { List list = new ArrayList(); list.add(8); list.add(2); list.add(3); list.add(10); List<Book> books = this.bookService.selectByIn(list); for (Book b : books){ System.out.println(b); } }
2.模糊查詢(三種方式)
2.1 參數中直接加入%%
2.2 使用${...}代替#{...}(不建議使用該方式,有SQL注入風險)
關鍵:#{...}與${...}區別?
參數類型為字符串,#會在前后加單引號['],$則直接插入值
注:
1) mybatis中使用OGNL表達式傳遞參數
2) 優先使用#{...}
3) ${...}方式存在SQL注入風險
2.3 SQL字符串拼接CONCAT
<!--模糊查詢--> <select id="selectByLike1" resultType="com.liuwenwu.model.Book" parameterType="java.lang.String"> select * from t_mvc_book where bname like #{bname} </select> <select id="selectByLike2" resultType="com.liuwenwu.model.Book" parameterType="java.lang.String"> select * from t_mvc_book where bname like '${bname}' </select> <select id="selectByLike3" resultType="com.liuwenwu.model.Book" parameterType="java.lang.String"> select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%') </select>
List<Book> selectByLike1(@Param("bname")String bname); List<Book> selectByLike2(@Param("bname")String bname); List<Book> selectByLike3(@Param("bname")String bname);
測試
@Test public void selectByLike() { // List<Book> books = this.bookService.selectByLike1(StringUtil.toLikeStr("聖墟")); // List<Book> books = this.bookService.selectByLike2("%聖墟% or bid !=1"); List<Book> books = this.bookService.selectByLike3("聖墟"); for (Book b : books){ System.out.println(b); } }
結果:
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>,適用於多表查詢返回單個結果集
<!--3、查詢返回結果集的處理--> <select id="list1" resultMap="BaseResultMap"> select * from t_mvc_book </select> <select id="list2" resultType="com.liuwenwu.model.Book"> select * from t_mvc_book </select> <select id="list3" resultType="com.liuwenwu.model.Book" parameterType="com.liuwenwu.model.BookVo"> select * from t_mvc_book where bid in <foreach collection="bookIds" open="(" close=")" separator="," item="bid"> #{bid} </foreach> </select> <select id="list4" resultType="java.util.Map" parameterType="java.util.Map"> select * from t_mvc_book <where> <if test="null != bname and bname !=''"> and bname like #{bname} </if> </where> </select> <select id="list5" resultType="java.util.Map" parameterType="java.util.Map"> select * from t_mvc_book <where> <if test="null != bid and bid !=''"> and bid = #{bid} </if> </where> </select>
// 3.1 使用resultMap返回自定義類型集合 List<Book> list1(); // 3.2 使用resultType返回List<T> List<Book> list2(); // 3.3 使用resultType返回單個對象 Book list3(BookVo bookVo); // 3.4 使用resultType返回List<Map>,適用於多表查詢返回結果集 List<Map> list4(Map map); // 3.5 使用resultType返回Map<String,Object>,適用於多表查詢返回單個結果集 Map list5(Map map);
測試:
@Test public void list() { // 返回一個resultMap但是使用list<T>接收 // List<Book> books = this.bookService.list1(); // 返回的是resulttype使用list<T>接收 // List<Book> books = this.bookService.list2(); // 返回的是resulttype使用list<T>接收 // for (Book b : books){ // System.out.println(b); // } // 返回的是resulttype使用T接收 // BookVo bookVo =new BookVo(); // List list = new ArrayList(); // list.add(2); // bookVo.setBookIds(list); // Book book = this.bookService.list3(bookVo); // System.out.println(book); // 返回的是resulttype使用list<Map>接收 Map map =new HashMap(); // map.put("bname",StringUtil.toLikeStr("聖墟")); // List<Map> list = this.bookService.list4(map); // for (Map m : list) { // System.out.println(m); // } // 返回的是resulttype使用Map接收 map.put("bid",2); Map m = this.bookService.list5(map); System.out.println(m); }
結果:
4.分頁查詢
為什么要重寫mybatis的分頁?
Mybatis的分頁功能很弱,它是基於內存的分頁(查出所有記錄再按偏移量offset和邊界limit取結果),在大數據量的情況下這樣的分頁基本上是沒有用的
使用分頁插件步奏
1、導入pom依賴
2、Mybatis.cfg.xml配置攔截器
3、使用PageHelper進行分頁
4、處理分頁結果
Pom依賴
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency>
Mybatis.cfg.xml配置攔截器
<plugins> <!-- 配置分頁插件PageHelper, 4.0.0以后的版本支持自動識別使用的數據庫 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> </plugin> </plugins>
<select id="list4" resultType="java.util.Map" parameterType="java.util.Map"> select * from t_mvc_book <where> <if test="null != bname and bname !=''"> and bname like #{bname} </if> </where> </select>
@Override public List<Map> listPager(Map map, PageBean pageBean) { if(pageBean!=null && pageBean.isPagination()){ PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); } List<Map> list = this.bookMapper.list4(map); if(pageBean!=null && pageBean.isPagination()){ PageInfo pageInfo =new PageInfo(list); System.out.println("當前的頁碼:"+pageInfo.getPageNum()); System.out.println("頁數據量:"+pageInfo.getPageSize()); System.out.println("符合條件的記錄數:"+pageInfo.getTotal()); pageBean.setTotal(pageInfo.getTotal()+""); } return list; }
測試:
@Test public void listPager() { Map map =new HashMap(); map.put("bname",StringUtil.toLikeStr("聖墟")); PageBean pageBean =new PageBean(); pageBean.setPage(3); // pageBean.setPagination(false); List<Map> list = this.bookService.listPager(map, pageBean); for (Map m : list) { System.out.println(m); } }
結果:
5.特殊字符處理
>(>)
<(<)
&(&)
空格( )
<![CDATA[ <= ]]>
<select id="list6" resultType="java.util.Map" parameterType="com.liuwenwu.model.BookVo"> select * from t_mvc_book <where> <if test="null != min and min !=''"> and price > #{min} </if> <if test="null != max and max !=''"> and price < #{max} </if> </where> </select> <select id="list7" resultType="java.util.Map" parameterType="com.liuwenwu.model.BookVo"> select * from t_mvc_book <where> <if test="null != min and min !=''"> <![CDATA[ and price > #{min} ]]> </if> <if test="null != max and max !=''"> <![CDATA[ and price < #{max} ]]> </if> </where> </select>
// 特殊字符的處理方式 List<Map> list6(BookVo bookVo); List<Map> list7(BookVo bookVo);
測試:
@Test public void listSpecoal() { BookVo bookVo =new BookVo(); bookVo.setMin(100.0); bookVo.setMax(500.0); // List<Map> list = this.bookService.list6(bookVo); List<Map> list = this.bookService.list7(bookVo); for (Map map : list) { System.out.println(map); } }
相關代碼
PageBean 分頁工具類
package com.liuwenwu.util; import java.io.Serializable; import java.util.Map; import javax.servlet.http.HttpServletRequest; public class PageBean implements Serializable { private static final long serialVersionUID = 2422581023658455731L; //頁碼 private int page=1; //每頁顯示記錄數 private int rows=10; //總記錄數 private int total=0; //是否分頁 private boolean isPagination=true; //上一次的請求路徑 private String url; //獲取所有的請求參數 private Map<String,String[]> map; public PageBean() { super(); } //設置請求參數 public void setRequest(HttpServletRequest req) { String page=req.getParameter("page"); String rows=req.getParameter("rows"); String pagination=req.getParameter("pagination"); this.setPage(page); this.setRows(rows); this.setPagination(pagination); this.url=req.getContextPath()+req.getServletPath(); this.map=req.getParameterMap(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getMap() { return map; } public void setMap(Map<String, String[]> map) { this.map = map; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public void setPage(String page) { if(null!=page&&!"".equals(page.trim())) this.page = Integer.parseInt(page); } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public void setRows(String rows) { if(null!=rows&&!"".equals(rows.trim())) this.rows = Integer.parseInt(rows); } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public void setTotal(String total) { this.total = Integer.parseInt(total); } public boolean isPagination() { return isPagination; } public void setPagination(boolean isPagination) { this.isPagination = isPagination; } public void setPagination(String isPagination) { if(null!=isPagination&&!"".equals(isPagination.trim())) this.isPagination = Boolean.parseBoolean(isPagination); } /** * 獲取分頁起始標記位置 * @return */ public int getStartIndex() { //(當前頁碼-1)*顯示記錄數 return (this.getPage()-1)*this.rows; } /** * 末頁 * @return */ public int getMaxPage() { int totalpage=this.total/this.rows; if(this.total%this.rows!=0) totalpage++; return totalpage; } /** * 下一頁 * @return */ public int getNextPage() { int nextPage=this.page+1; if(this.page>=this.getMaxPage()) nextPage=this.getMaxPage(); return nextPage; } /** * 上一頁 * @return */ public int getPreivousPage() { int previousPage=this.page-1; if(previousPage<1) previousPage=1; return previousPage; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination + "]"; } }
Bookvo
vo用來存放包括數據庫表映射的字段以及多余的查詢條件所需屬性列,保證實體類純粹,降低耦合度
package com.liuwenwu.model; import java.util.List; /** * @author LWW * @site www.lww.com * @company * @create 2019-09-20 19:05 * vo用來存放包括數據庫表映射的字段以及多余的查詢條件所需屬性列 */ public class BookVo extends Book{ private List<String> bookIds; private Double min; private Double max; public Double getMax() { return max; } public void setMax(Double max) { this.max = max; } public Double getMin() { return min; } public void setMin(Double min) { this.min = min; } public List<String> getBookIds() { return bookIds; } public void setBookIds(List<String> bookIds) { this.bookIds = bookIds; } }
BookService
package com.liuwenwu.service; import com.liuwenwu.model.Book; import com.liuwenwu.model.BookVo; import com.liuwenwu.util.PageBean; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * @author LWW * @site www.lww.com * @company * @create 2019-09-19 22:23 */ public interface BookService { int deleteByPrimaryKey(Integer bid); int insert(Book record); int insertSelective(Book record); Book selectByPrimaryKey(Integer bid); int updateByPrimaryKeySelective(Book record); int updateByPrimaryKey(Book record); List<Book> selectByIn(List bookIds); List<Book> selectByLike1(String bname); List<Book> selectByLike2(String bname); List<Book> selectByLike3(String bname); List<Book> list1(); List<Book> list2(); Book list3(BookVo bookVo); List<Map> list4(Map map); Map list5(Map map); List<Map> listPager(Map map, PageBean pageBean); List<Map> list6(BookVo bookVo); List<Map> list7(BookVo bookVo); }
BookServiceImpl
package com.liuwenwu.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.liuwenwu.mapper.BookMapper; import com.liuwenwu.model.Book; import com.liuwenwu.model.BookVo; import com.liuwenwu.service.BookService; import com.liuwenwu.util.PageBean; import java.util.List; import java.util.Map; /** * @author LWW * @site www.lww.com * @company * @create 2019-09-19 22:58 */ public class BookServiceImpl implements BookService { private BookMapper bookMapper; public BookMapper getBookMapper() { return bookMapper; } public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int deleteByPrimaryKey(Integer bid) { return bookMapper.deleteByPrimaryKey(bid); } @Override public int insert(Book record) { return bookMapper.insert(record); } @Override public int insertSelective(Book record) { return bookMapper.insertSelective(record); } @Override public Book selectByPrimaryKey(Integer bid) { return bookMapper.selectByPrimaryKey(bid); } @Override public int updateByPrimaryKeySelective(Book record) { return bookMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(Book record) { return bookMapper.updateByPrimaryKey(record); } @Override public List<Book> selectByIn(List bookIds) { return bookMapper.selectByIn(bookIds); } @Override public List<Book> selectByLike1(String bname) { return bookMapper.selectByLike1(bname); } @Override public List<Book> selectByLike2(String bname) { return bookMapper.selectByLike2(bname); } @Override public List<Book> selectByLike3(String bname) { return bookMapper.selectByLike3(bname); } @Override public List<Book> list1() { return bookMapper.list1(); } @Override public List<Book> list2() { return bookMapper.list2(); } @Override public Book list3(BookVo bookVo) { return bookMapper.list3(bookVo); } @Override public List<Map> list4(Map map) { return bookMapper.list4(map); } @Override public Map list5(Map map) { return bookMapper.list5(map); } @Override public List<Map> listPager(Map map, PageBean pageBean) { if(pageBean!=null && pageBean.isPagination()){ PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); } List<Map> list = this.bookMapper.list4(map); if(pageBean!=null && pageBean.isPagination()){ PageInfo pageInfo =new PageInfo(list); System.out.println("當前的頁碼:"+pageInfo.getPageNum()); System.out.println("頁數據量:"+pageInfo.getPageSize()); System.out.println("符合條件的記錄數:"+pageInfo.getTotal()); pageBean.setTotal(pageInfo.getTotal()+""); } return list; } @Override public List<Map> list6(BookVo bookVo) { return bookMapper.list6(bookVo); } @Override public List<Map> list7(BookVo bookVo) { return bookMapper.list7(bookVo); } }