mybaits的动态sql及模糊查询与分页

文章目录

  • mybaits动态sql
  • 模糊查询
  • 查询返回结果集的处理
  • 分页查询
  • 特殊字符处理

mybaits动态sql

if
如果name不为空,就进行拼接if体

 
        #{bname,jdbcType=VARCHAR},
      

trim
trim则是去空格。

  <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=REAL},
      if>
    trim>

foreach
collection 对应的是你要遍历的集合,这里我是从接口那边定义传过来的。
open 是当循环开始时在前面加的字符。
close 是当循环结束时在后面加的字符。
separator 是使用什么隔开。
item 则是代表着集合中的每个元素。

 <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
       #{bid}
    foreach>

模糊查询

接口

//    模糊查询三种方法
    List<Book> selectBylike1(@Param("bname") String bname);
    List<Book> selectBylike2(@Param("bname") String bname);
    List<Book> selectBylike3(@Param("bname") String bname);

xml配置


  <select id="selectBylike1" resultType="com.tzp.model.Book" parameterType="java.lang.String">
      select * from t_mvc_book where bname like #{bname}
  select>
  <select id="selectBylike2" resultType="com.tzp.model.Book">
      select * from t_mvc_book where bname like '${bname}'
  select>
  <select id="selectBylike3" resultType="com.tzp.model.Book">
    select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
  select>

测试

 public void selectBylike() {
        List<Book> bb = this.bookService.selectBylike1(StringUtils.toLikeStr("圣墟"));
//        List bb = this.bookService.selectBylike2(StringUtils.toLikeStr("圣墟"));
//        List bb = this.bookService.selectBylike3(StringUtils.toLikeStr("圣墟"));

        for (Book book : bb) {
            System.out.println(book);
        }
    }

mybaits的动态sql及模糊查询与分页_第1张图片

mybaits里面的 #传参与 $ 传参有什么区别?
也是就是上面的第一种的方法和第二种方法的区别

  1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
    如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by ‘111’,
    如果传入的值是id,则解析成的sql为order by “id”.

  2. $将传入的数据直接显示生成在sql中。
    如:order by u s e r i d user_id userid,如果传入的值是111,那么解析成sql时的值为order by user_id,
    如果传入的值是id,则解析成的sql为order by id.

  3. #方式能够很大程度防止sql注入。

  4. $方式无法防止Sql注入。

  5. $方式一般用于传入数据库对象,例如传入表名.

  6. 一般能用#的就别用$.
    mybaits的动态sql及模糊查询与分页_第2张图片

查询返回结果集的处理

resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型

在第一种方法中就使用了这个BaseResultMap

  <resultMap id="BaseResultMap" type="com.cpc.model.User" >
    <constructor >
      <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="pwd" jdbcType="VARCHAR" javaType="java.lang.String" />
    constructor>
  resultMap>

BookVo类用来存放包括数据库表映射字段以及多余查询条件所需属性


public class BookVo extends Book{
    private List 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 getBookIds() {
        return bookIds;
    }

    public void setBookIds(List bookIds) {
        this.bookIds = bookIds;
    }
}

接口
后两种方法使用于适用于多表查询返回单个结果集

   //    3.1 使用resultMap返回自定义类型集合
    List<Book> list1();
    //    3.2 使用resultType返回List
    List<Book> list2();
    //    3.3 使用resultType返回单个对象
    Book list3(BookVo bookVo);
    //    3.4 使用resultType返回List,适用于多表查询返回结果集
    List<Map>  list4(Map map);
    //    3.5 使用resultType返回Map,适用于多表查询返回单个结果集
    Map list5(Map map);

第一种方法要写一个拼接sql方法 使用resultMap返回自定义类型集合


public class StringUtils {
    public static String toLikeStr(String str){
        return "%"+str+"%";
    }

}

xml配置

<select id="list1" resultMap="BaseResultMap">
    select * from t_mvc_book
  select>
  <select id="list2" resultType="com.tzp.model.Book">
    select * from t_mvc_book
  select>
  <select id="list3" resultType="com.tzp.model.Book" parameterType="com.tzp.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 like #{bid}
        if>
      where>
  select>

测试

 @Test
    public void list() {
//        返回redultMap但是使用list
//        List books = this.bookService.list1();
//        返回redulttype但是使用list
//        List books = this.bookService.list2();
//
//        for (Book book : books) {
//
//            System.out.println(book);
//        }

//        返回的是resultype使用接收
//        BookVo bookVo = new BookVo();
//        List list = new ArrayList();
//        list.add(27);
//        bookVo.setBookIds(list);
//        Book book = this.bookService.list3(bookVo);
//        System.out.println(book);

//        返回的是resultype,然后使用list进行接收
        Map map = new HashMap();
//        map.put("bname",StringUtils.toLikeStr("圣墟"));
//        List list = this.bookService.list4(map);
//        for (Map m : list) {
//            System.out.println(m);
//        }

//        返回的是resuType,然后使用Map进行接收
        map.put("bid",27);
        Map map1 = this.bookService.list5(map);
        System.out.println(map1);

    }

分页查询

为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的

使用分页插件步奏
1、导入pom依赖

<dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelperartifactId>
    <version>5.1.2version>
dependency>

2、Mybatis.cfg.xml配置拦截器
要配在配置mybatis运行环境上面

<plugins>
    
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
    plugin>
plugins>

3、使用PageHelper进行分页
工具类PageBean

package com.tzp.util;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

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
				+ "]";
	}
}

BookService 的接口方法

//    分页查询
    List<Map>  listPager(Map map, PageBean pageBean);

在实现类BookServiceImpl实现这个方法

 @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;
    }

4、处理分页结果
测试

   @Test
    public void listPager() {
        Map map = new HashMap();
        map.put("bname",StringUtils.toLikeStr("圣墟"));
        PageBean pageBean = new PageBean();
        pageBean.setPage(3);
//        控制是否分页
        pageBean.setPagination(false);
        List<Map> maps = this.bookService.listPager(map, pageBean);
        for (Map m : maps) {
            System.out.println(m);
        }
    }

mybaits的动态sql及模糊查询与分页_第3张图片

特殊字符处理

在mybaits中,不是使用大于或者小于符号,它是会报错的,他有专门的方法来表示的。

第一种方式:
大于:>
小于:<
空格:&

接口

 List  list6(BookVo bookVo);

xml配置

  <select id="list6" resultType="java.util.Map" parameterType="com.tzp.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>

测试

    @Test
    public void sqlSpecial() {
        BookVo bookVo = new BookVo();
        bookVo.setMax(30);
        bookVo.setMin(20);
        List<Map> maps = this.bookService.list6(bookVo);
        for (Map m : maps) {
            System.out.println(m);
        }
    }

第二种方式:
在sql语句前加上

后加上 ]]>

接口

List<Map>  list7(BookVo bookVo);

xml配置

<select id="list7" resultType="java.util.Map" parameterType="com.tzp.model.BookVo">
      select * from t_mvc_book
      <where>
        <if test="null != min and min != ''">
          
        if>
        <if test="null != max and max != ''">
          
        if>
    where>
select>

你可能感兴趣的:(mybatis,Java)