mybatis(动态SQL,结果集处理,分页,特殊字符处理)

目标

1、mybatis动态sql
2、模糊查询
3、查询返回结果集的处理
4、分页查询
5、特殊字符处理

用到的工具类
PageBean

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

在参数前面加上@Param(“bookIds”)的作用是在Mapper.xml中可以使用,里面放的是别名
List<Book> selectByIn(@Param("bookIds") List bookIds);

StringUtils

package yinyi.util;

/**
 * @author殷熠
 * @site
 * @company
 * @create  2019-09-21 15:39
 */
public class StringUtils {
    public static String toLikeStr(String str){
        return "%"+str+"%";
    }
}

BookVo


/*用来处理查询条件用到的而又不是数据库的字段的属性*/
package yinyi.model;

import java.util.List;

/**
 * @author殷熠
 * @site
 * @company
 * @create  2019-09-21 16:32
 *
 * vo用来存放包括数据库表映射以及多余查询条件所需属性
 *
 */
public class BookVo {
    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;
    }

}


BookMapper

/*模糊查定义参数需要声明名(@Param),在xml中需要声明参数类型*/
package yinyi.mapper;

import org.apache.ibatis.annotations.Param;
import yinyi.model.Book;
import yinyi.model.BookVo;

import java.util.List;
import java.util.Map;

public interface BookMapper {
    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(@Param("bookIds")List bookIds);

    List<Book> selectByIn1(@Param("bname")String  bname);
    List<Book> selectByIn2(@Param("bname")String  bname);
    List<Book> selectByIn3(@Param("bname")String  bname);

//    3.1 使用resultMap返回自定义类型集合
        List<Book> lsit1();
//    3.2 使用resultType返回List<T>
        List<Book> lsit2();
//    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);
//      处理特殊字符的方式
        Map list6(BookVo bookVo);
        Map list7(BookVo bookVo);
}

BookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="yinyi.mapper.BookMapper" >
  <resultMap id="BaseResultMap" type="yinyi.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>
  <sql id="Base_Column_List" >
    bid, bname, price
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_mvc_book
    where bid = #{bid,jdbcType=INTEGER}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_mvc_book
    where bid = #{bid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="yinyi.model.Book" >
    insert into t_mvc_book (bid, bname, price
      )
    values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
      )
  </insert>
  <insert id="insertSelective" parameterType="yinyi.model.Book" >
    insert into t_mvc_book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        bid,
      </if>
      <if test="bname != null" >
        bname,
      </if>
      <if test="price != null" >
        price,
      </if>
    </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>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="yinyi.model.Book" >
    update t_mvc_book
    <set >
      <if test="bname != null" >
        bname = #{bname,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        price = #{price,jdbcType=REAL},
      </if>
    </set>
    where bid = #{bid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="yinyi.model.Book" >
    update t_mvc_book
    set bname = #{bname,jdbcType=VARCHAR},
      price = #{price,jdbcType=REAL}
    where bid = #{bid,jdbcType=INTEGER}
  </update>


    <!-- <foreach>的使用-->
  <select id="selectByIn" resultType="yinyi.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>


    <select id="selectByIn1" resultType="yinyi.model.Book" parameterType="java.lang.String">/*方式一*/
        select  * from  t_mvc_book where bname like #{bnaem}
    </select>

    <select id="selectByIn2" resultType="yinyi.model.Book" parameterType="java.lang.String">/*方式二*/
        select  * from  t_mvc_book where bname like '${bname}'
    </select>

    <select id="selectByIn3" resultType="yinyi.model.Book" parameterType="java.lang.String">/*方式三*/
        select  * from  t_mvc_book where bname like (concat('%',#(bname),'%')
    </select>


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

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

    <select id="list3" resultType="yinyi.model.Book" parameterType="yinyi.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>

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

</mapper>

分页:

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

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>

BookService

package yinyi.service;

import org.apache.ibatis.annotations.Param;
import yinyi.model.Book;
import yinyi.model.BookVo;
import yinyi.util.PageBean;

import java.util.List;
import java.util.Map;

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> selectByIn1(String  bname);
    List<Book> selectByIn2(String  bname);
    List<Book> selectByIn3(String  bname);

    List<Book> lsit1();
    List<Book> lsit2();
    Book list3 (BookVo bookVo);
    List<Map> list4(Map map);
    Map list5(Map map);

    List<Map> listPager(Map map,PageBean pageBean);

    Map list6(BookVo bookVo);
    Map list7(BookVo bookVo);
}

BookServiceImpl

package yinyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import yinyi.model.Book;
import yinyi.mapper.BookMapper;
import yinyi.model.BookVo;
import yinyi.service.BookService;
import yinyi.util.PageBean;

import java.util.List;
import java.util.Map;

/**@author 殷熠
 * @company
 * @create  2019-09-20  22:30
 */
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> selectByIn1(String bname) {
        return bookMapper.selectBylike1(bname);
    }

    @Override
    public List<Book> selectByIn2(String bname) {
        return bookMapper.selectBylike2(bname);
    }

    @Override
    public List<Book> selectByIn3(String bname) {
        return bookMapper.selectBylike3(bname);
    }

    @Override
    public List<Book> lsit1() {
        return bookMapper.list1();
    }

    @Override
    public List<Book> lsit2() {
        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 book) {
        return bookMapper.list5(book);
    }

    @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.getSize());
            System.out.println("总记录数:"+pageInfo.getTotal());
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return list;
    }

//特殊字符
    @Override
    public Map list6(BookVo bookVo) {
        return BookMapper.list6(BookVo);
    }

    @Override
    public Map list7(BookVo bookVo) {
        return  BookMapper.list7(BookVo);
    }


}

测试代码:MapperSqlTest

package yinyi.test;

import org.apache.ibatis.session.SqlSession;
import yinyi.mapper.BookMapper;
import yinyi.model.Book;
import yinyi.model.BookVo;
import yinyi.service.BookService;
import yinyi.service.impl.BookServiceImpl;
import yinyi.util.PageBean;
import yinyi.util.SessionUtil;
import yinyi.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MapperSqlTest {
    private BookService bookService;
    private SqlSession sqlSession;

    @Before
    public void setUp() throws Exception {
        BookServiceImpl bookServiceImpl = new BookServiceImpl();
        sqlSession = SessionUtil.openSession();
        bookServiceImpl.setBookMapper(sqlSession.getMapper(BookMapper.class));
        this.bookService = bookServiceImpl;
    }

    @After
    public void tearDown() throws Exception {
        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void selectByIn() {
        List list = new ArrayList();
        list.add(2);
        list.add(5);
        list.add(19);
        list.add(27);
        List<Book> books = this.bookService.selectByIn(list);
        for (Book b : books) {
            System.out.println(b);
        }
    }

    /**
     * 模糊查
     */
    @Test
    public void selectBylike() {
//        List<Book> books = this.bookService.selectBylike1(StringUtils.toLikeStr("圣墟"));
//        ${}需要在外面加引号,存在sql攻击的可能
//        List<Book> books = this.bookService.selectBylike2("%圣墟 or bid !=1%");
        List<Book> books = this.bookService.selectByIn3("圣墟");
        for (Book book : books) {
            System.out.println(book);
        }
    }


    /**
     * 结果集处理
     */
    @Test
        public void list() {
//        返回一个resultMap但是使用list<T>
//        List<Book> books = this.bookService.list1();
//        返回的是resulttype使用list<T>接收
//        List<Book> books = this.bookService.list2();
//        for (Book b : books) {
//            System.out.println(b);
//        }

//        返回的是resulttype使用<T>接收
//        BookVo bookVo=new BookVo();
//        List list=new ArrayList();
//        list.add(27);
//        bookVo.setBookIds(list);
//        Book book = this.bookService.list3(bookVo);
//        System.out.println(book);
//
//        返回的是resulttype,然后用List<Map>进行接收
           Map map = new HashMap<>();
//        map.put("bname", StringUtils.toLikeStr("圣墟"));
//        List<Map> list=this.bookService.list4(map);
//        for (Map m : list) {
//            System.out.println(m);
//        }

//        5、返回的是resultType,然后用List<Map>进行接收
            map.put("bid", 27);
            Map m = this.bookService.list5(map);
            System.out.println(m);
    }

    /**
     * 分页
     */
    @Test
    public void listPage() {
        Map map = new HashMap();
        map.put("bname", StringUtils.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);
        }
    }

    /**
     * 特殊字符处理
     */
    @Test
    public void sqlSpecial() {
        BookVo bookVo = new BookVo();
        bookVo.setMax(30);
        bookVo.setMin(20);
//        List<Map> list = this.bookService.list6(bookVo);
       List<Map> list = this.bookService.list7(bookVo);
        for (Map m : list) {
            System.out.println(m);
        }
    }
}

感谢您的观看,本次的分享就到此结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值