前言:Mybatis的动态sql和分页要在完成Mubatis入门搭建下实现
Mybatis动态sql
trim:去空格
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="bid != null">
bid,
</if>
<if test="bname != null">
bname,
</if>
<if test="price != null">
price,
</if>
</trim>
if:如果 name 不为空 就进行if体拼接
<if test="bid != null">
bid,
</if>
<if test="bname != null">
bname,
</if>
<if test="price != null">
price,
</if>
foreach:遍历集合 批量查询 通常用于in关键字
<select id="selectBooksIn" resultType="com.xwt.model.Book">
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</select>
List<Book> selectBooksIn(@Param("bookIds") List bookIds);
模糊查询
#{...}
${...}
Concat
注:1) mybatis中使用OGNL表达式传递参数
2) 优先使用#{...}
3) #{...}自带引号,${...}有sql注入的风险
BookMapper
List<Book> selectBooksLike1(@Param("bname")String bname);
List<Book> selectBooksLike2(@Param("bname")String bname);
List<Book> selectBooksLike3(@Param("bname")String bname);
BookMapper.xml
<select id="selectBooksLike1" resultType="com.xwt.model.Book" parameterType="java.lang.String">
select * from t_mvc_book
<where>
bname like #{bname}
</where>
</select>
<select id="selectBooksLike2" resultType="com.xwt.model.Book" parameterType="java.lang.String">
select * from t_mvc_book
<where>
bname like '${bname}'
</where>
</select>
<select id="selectBooksLike3" resultType="com.xwt.model.Book" parameterType="java.lang.String">
select * from t_mvc_book
<where>
bname like concat('%',#{bname},'%')
</where>
</select>
BookService
List<Book> selectBookLike1(String bname);
List<Book> selectBookLike2(String bname);
List<Book> selectBookLike3(String bname);
BookServiceImpl
@Override
public List<Book> selectBookLike1(String bname) {
return bookMapper.selectBookLike1(bname);
}
@Override
public List<Book> selectBookLike2(String bname) {
return bookMapper.selectBookLike2(bname);
}
@Override
public List<Book> selectBookLike3(String bname) {
return bookMapper.selectBookLike3(bname);
}
测试类BookServiceImplTest
@Test
//模糊查询
public void selectBooksLike1(){
for (Book book : this.bookService.selectBooksLike1("%圣墟%")) {
System.out.println(book);
}
}
@Test
public void selectBooksLike2(){
for (Book book : this.bookService.selectBooksLike2("%圣墟%")) {
System.out.println(book);
}
}
@Test
public void selectBooksLike3(){
for (Book book : this.bookService.selectBooksLike3("圣墟")) {
System.out.println(book);
}
}
运行都如下:
查询返回结果集的处理
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
① 使用resultMap返回自定义类型集合
② 使用resultType返回List
③ 使用resultType返回单个对象
④ 使用resultType返回List
BookVo
package com.xwt.model;
import java.util.List;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-16 15:28
*
* vo类专门用来封装多表联查信息用于展示的
* 封装查询条件
*/
public class BookVo extends Book{
private List<Integer> bookIds;
public List<Integer> getBookIds() {
return bookIds;
}
public void setBookIds(List<Integer> bookIds) {
this.bookIds = bookIds;
}
}
BookMapper BookService
List<Book> list1();
List<Book> list2();
List<Book> list3(BookVo bookVo);
List<Map> list4();
Map list5(Map map);
BookMapper.xml
<select id="list1" resultMap="BaseResultMap">
select * from t_mvc_book
</select>
<select id="list2" resultType="com.xwt.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.xwt.model.Book" parameterType="com.xwt.model.BookVo">
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</select>
<select id="list4" resultType="java.util.Map">
select * from t_mvc_book
</select>
<select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bid = #{bid}
</select>
BookServiceImpl
@Override
public List<Book> list1() {
return bookMapper.list1();
}
@Override
public List<Book> list2() {
return bookMapper.list2();
}
@Override
public List<Book> list3(BookVo bookVo) {
return bookMapper.list3(bookVo);
}
@Override
public List<Map> list4() {
return bookMapper.list4();
}
@Override
public Map list5(Map map) {
return bookMapper.list5(map);
}
测试类BookServiceImplTest
@Test
//结果集处理
public void list1(){
for (Book book : this.bookService.list1()) {
System.out.println(book);
}
}
@Test
public void list2(){
for (Book book : this.bookService.list2()) {
System.out.println(book);
}
}
@Test
public void list3(){
BookVo bookVo=new BookVo();
List bookIds =new ArrayList();
bookIds.add(16);
bookIds.add(20);
bookIds.add(21);
bookVo.setBookIds(bookIds);
for (Book book : this.bookService.list3(bookVo)) {
System.out.println(book);
}
}
@Test
public void list4(){
for (Map map : this.bookService.list4()) {
System.out.println(map);
}
}
@Test
public void list5(){
Map map=new HashMap();
map.put("bid",20);
System.out.println(this.bookService.list5(map));
}
分页查询
为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的
使用分页插件步奏
1、导入pom依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2、Mybatis.cfg.xml配置拦截器
<plugins>
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
3、使用PageHelper进行分页
PageBean
package com.xwt.util;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-16 16:40
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
// 保留上一次的请求地址
private String url;
// 保留上一次请求所携带的参数
private Map<String, String[]> paMap = new HashMap<>();
/**
* pageBean初始化
* @param req
*/
public void setRequest(HttpServletRequest req) {
//改变它第几页的数据
this.setPage(req.getParameter("page"));
//改变它每页展示的数据
this.setRows(req.getParameter("rows"));
//控制页面是否分页
this.setPagination(req.getParameter("pagination"));
this.setUrl(req.getRequestURL().toString());
this.setPaMap(req.getParameterMap());
}
public void setPagination(String parameter) {
// 当你填false就不分页
if("false".equals(pagination)) {
this.setPagination(false);
}
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(Integer.valueOf(rows));
}
}
public void setPage(String page) {
// 如果不为空的时候
if(StringUtils.isNotBlank(page)){
this.setPage(Integer.valueOf(page));
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getPaMap() {
return paMap;
}
public void setPaMap(Map<String, String[]> paMap) {
this.paMap = paMap;
}
private boolean pagination = true;// 是否分页
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = 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 pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
/**
* 最大页码
* @return
*/
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows + 1;
}
/**
* 获取下一页
* @return
*/
public int getNextPage() {
return this.page < this.getMaxPage() ? this.page+1 : this.page;
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
return this.page > 1 ? this.page-1 : this.page;
}
}
StringUtils
package com.xwt.util;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-16 16:41
*/
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
BookMapper
List<Map> listPager(Map map);
BookService
List<Map> listPager(Map map, PageBean pageBean);
BookMapper.xml
<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book
<where>
<if test="bname != null and bname != ''">
bname like #{bname}
</if>
</where>
</select>
4、处理分页结果
BookServiceImpl
@Override
public List<Map> listPager(Map map, PageBean pageBean) {
if (pageBean!=null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
List<Map>list = bookMapper.listPager(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());
//用于下一次分页
System.out.println(pageBean.getTotal() + "");
}
return list;
}
测试类BookServiceImplTest
@Test
public void listPager(){
Map map=new HashMap();
map.put("bname","%圣墟%");
PageBean pageBean=new PageBean();
//不分页
pageBean.setPagination(false);
pageBean.setPage(3);
for (Map m : this.bookService.listPager(map, pageBean)) {
System.out.println(m);
}
}
特殊字符处理
>(>)
<(<)
&(&)
空格( )
<![CDATA[ <= ]]>
BookVo
package com.xwt.model;
import java.util.List;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-16 15:28
*
* vo类专门用来封装多表联查信息用于展示的
* 封装查询条件
*/
public class BookVo extends Book{
private List<Integer> bookIds;
private Float min;
private Float max;
public Float getMin() {
return min;
}
public void setMin(Float min) {
this.min = min;
}
public Float getMax() {
return max;
}
public void setMax(Float max) {
this.max = max;
}
public List<Integer> getBookIds() {
return bookIds;
}
public void setBookIds(List<Integer> bookIds) {
this.bookIds = bookIds;
}
}
BookMapper.xml
<select id="list6" resultType="com.xwt.model.Book" parameterType="com.xwt.model.BookVo">
select * from t_mvc_book where <![CDATA[ price > #{min} and price < #{max} ]]>
</select>
BookServiceImpl
@Override
public List<Book> list6(BookVo bookVo) {
return bookMapper.list6(bookVo);
}
测试类BookServiceImplTest
@Test
public void list6() {
BookVo bookVo = new BookVo();
bookVo.setMin(10f);
bookVo.setMax(20f);
for (Book book : this.bookService.list6(bookVo)) {
System.out.println(book);
}
}