小言_互联网的博客

mybatis动态SQL以及分页

426人阅读  评论(0)

1、mybatis动态sql

1.1if

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

      <if test="name != null" >
        #{name,jdbcType=VARCHAR}, <! -- 这就是if-->
      </if>

1.2trim

一样的sql语句拼接:prefix前缀,suffi 后缀。suffixOverrides 后缀覆盖

<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>

1.3 foreach

foreach 就是循环的意思,collection代表要被循环参数集合。open和close代表开始和结束拼接字符串。separator代表item之间的分割符。item就是当前正在循环的变量定义。就当java中的foreach看就能看懂了

<select id="selectByIn" resultType="com.hu.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>

2、模糊查询

模糊查小编这里演示3种方式:

    List<Book> selectByLike1(@Param("bname") String bname);

    List<Book> selectByLike2(@Param("bname") String bname);

    List<Book> selectByLike3(@Param("bname") String bname);

映射文件:

<select id="selectByLike1" resultType="com.hu.model.Book" parameterType="java.lang.String">
    select * from t_mvc_book where bname like #{bname}

  </select>

  <select id="selectByLike2" resultType="com.hu.model.Book" parameterType="java.lang.String">
    select * from t_mvc_book where bname like '${bname}'
  </select>

  <select id="selectByLike3" resultType="com.hu.model.Book" parameterType="java.lang.String">
    select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
  </select>

StringItils.toLikeString方法拼接

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

}

测试:

   @Test
    public void selectByLike() {
//        List<Book> books =  this.bookService.selectByLike1(StringItils.toLikeStr("圣墟"));
//        List<Book> books =  this.bookService.selectByLike2(StringItils.toLikeStr("圣墟"));
        List<Book> books = this.bookService.selectByLike3("圣墟");
        for (Book b : books){
            System.out.println(b);
        }
    }

注意:#{…}自带引号,${…}有sql注入的风险。第三中方式是MySQL的函数拼接方式,也是企业里常用的一种

测试:

2.1MyBatis中#和$的区别

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

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

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

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

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

  6. 一般能用#的就别用$.

3、查询返回结果集的处理

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

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

package com.hu.model;

import java.util.List;

/**
 * @author hu
 * @site www.huguiyun.xzy
 * @company xxx公司
 * @create  2019-09-21 13:02
 *
 * vo用来存放包括数据库
 */
public class BookVo extends Book {
    private List<String> 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<String> getBookIds(){
        return bookIds;
    }

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

}

3.1 使用resultMap返回自定义类型集合

实体类的配置类型

  <resultMap id="BaseResultMap" type="com.hu.model.Book" >
    <constructor >
      <idArg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
    </constructor>
  </resultMap>

接口:

  List<Book> list1();

映射文件:
这里的BaseResultMap就是上面的实体类的文件

  <select id="list1" resultMap="BaseResultMap">
    select * from t_mvc_book
  </select>

3.2 使用resultType返回List

接口:

List<Book> list2();

配置文件:

<select id="list2" resultMap="com.hu.model.Book">
    select * from t_mvc_book
  </select>

3.3 使用resultType返回单个对象

接口:

Book list3(BookVo bookVo);

配置文件:

<select id="list3" resultType="com.hu.model.Book" parameterType="com.hu.model.BookVo">
    select * from t_mvc_book where bid in
    <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
      #{bid}
    </foreach>
  </select>

3.4 使用resultType返回List,适用于多表查询返回结果集

接口:

List<Map> list4(Map map);

配置文件:

<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>

3.5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集

接口:

Map list5(Map map);

配置文件:

<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 lsit() {
        //返回resuletMap但是使用list<T>
        //List<Book> books = this.bookService.list1();

        //返回resulettype但是使用list<T>接受
//        List<Book> books = this.bookService.list2();
//        for (Book b : books){
//            System.out.println(b);
//        }
//

//        返回的是resulettpe使用T接受
//        BookVo bookVo = new BookVo();
//        List list = new ArrayList();
//        list.add(27);
//        bookVo.setBookIds(list);
//        this.bookService.list3(bookVo);

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

//
        Map map = new HashMap();
        map.put("bid",27);
        Map m = this.bookService.list5(map);
        System.out.println(m);

    }

4、分页查询

准备好pagBean

package com.hu.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
				+ "]";
	}
}

1、导入pom依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>

2、Mybatis.cfg.xml配置拦截器

这个拦截器一定要写在 配置mybatis运行环境 的上面,不然会有错误的

<plugins>
    <!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
    </plugin>
</plugins>

3、使用PageHelper进行分页

@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",StringItils.toLikeStr("圣墟"));
        PageBean pageBean = new PageBean();
        pageBean.setPage(3);//设置页码
        List<Map> list = this.bookService.listpager(map,pageBean);
        for (Map m: list){
            System.out.println(m);
        }
    }

5、特殊字符处理

两种:

>(&gt;)   
    <(&lt;)  
    &(&amp;) 
 空格(&nbsp;)


 <![CDATA[ <= ]]> 

具体实现:

 <select id="list6" resultType="java.util.Map" parameterType="com.hu.model.BookVo">
    select * from t_mvc_book
    <where>
      <if test="null != min and min !=''">
        and price &gt; #{min}
      </if>
      <if test="null != max and max !=''">
        and price &lt; #{max}
      </if>
    </where>
  </select>


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

转载:https://blog.csdn.net/what_where/article/details/101109023
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场