redis缓存实际应用

mybatis动态sql

if

if不为空name就自动拼接

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

trim

prefix代表前缀,suffi代表 后缀。suffixOverrides 在后缀后面添加

  <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="pwd != null" >
        pwd,
      </if>
    </trim>

foreach

open和close代表开始和结束拼接字符串。separator代表item之间的分割符。item就是当前正在循环的变量定义。

<select id="selectByIn" resultType="com.xyx.model.User" parameterType="java.util.List">
        select * from user where id in
        <foreach collection="userIds" open="(" close=")" separator="," item="uid">
            #{uid}
        </foreach>
  </select>

上面的与下面的是对应的

List<User> selectByIn(@Param("userIds") List userIds);

模糊查询的三种方式

 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.xyx.model.Book" parameterType="java.lang.String">
    select * from t_mvc_book where bname like #{bname}

  </select>

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

  <select id="selectByLike3" resultType="com.xyx.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攻击所以无特殊情况不用
在这里插入图片描述

查询返回结果集的处理

resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
bookVo 用来存放包括数据库表映射字段以及多余查询条件所用到的属性
bookVo

package com.xyx.model;

import java.util.List;

/**
 * @author xyx
 * @site www.xyxmage.com
 * @company xxx公司
 * @create 2019-09-22 10:10
 *
 * vo用来存放表包括数据库表映射字段以及多余查询条件所需要的属性
 */
public class BookVo {
    private List<String> bookIds;
    private float min;
    private float max;

    public float getMax() {
        return min;
    }

    public void setMax(float max) {
        this.max = max;
    }

    public float getMin() {
        return min;
    }

    public void setMin(float min) {
        this.min = min;
    }

    public List<String> getBookIds() {
        return bookIds;
    }

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

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

实体类的配置类型

<resultMap id="BaseResultMap" type="com.xyx.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>

使用resultType返回List

接口

List<Book> list2();

配置文件

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

使用resultType返回单个对象

接口

Book list3(BookVo bookVo);

配置文件

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

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

使用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 list() {
        //返回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);

    }

分页查询

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

导入pop依赖

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

Mybatis.cfg.xml配置拦截器

注意:拦截器一定要写在 配置mybatis运行环境 的上面不然会报错

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

使用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;
    }

处理分页结果
测试代码:

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

在这里插入图片描述

特殊字符处理的两种方式的两种方式

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


 2:<![CDATA[ <= ]]> 

实现

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值