mybatis动态sql以及分页


mybatis是什么和如何下载,基本搭建环境我在上篇博客中有详细解说,有兴趣的朋友可以去瞧瞧。(我使用的是idea工具)

接下来是为大家讲解一些基础的sql运用。

(在你生成好了sql文件和映射文件、Mapper接口还有实体类文件的前提下)

首先Mapper.xml是存放sql语句的地方,这里可以看到你可以运用的所有sql方法。

定义方法

你如果要自己在自定义方法,
第一步是在mapper接口中定义:
此文件里一开始就有一些最基本的sql。
这里我定义一个工具ID查找书本的方法。
在参数前面加上@Param(“bookIds”)的作用是在Mapper.xml中可以使用,里面放的是别名。

package com.zlk.mapper;

import com.zlk.model.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

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

在Mapper接口中定义好方法,然后alt + 回车。选择下图所示。
在这里插入图片描述
这是在把刚才写好的方法生成sql模块。你可以看到在Mapper.xml中出现的sql模块:
在这里插入图片描述
接下来是配置好这些sql:
resultType 是你返回来的数据类型,
parameterType 是你参数的数据类型,
select中间就是你要执行的sql语句,

在这里插入图片描述

动态sql

可以看到我这里在select中使用了foreach,这就是mybatis动态sql,
除了foreach还有if,trim if即是判断,trim则是去空格。
foreach使用规则:
collection 对应的是你要遍历的集合,这里我是从接口那边定义传过来的。
open 是当循环开始时在前面加的字符。
close 是当循环结束时在后面加的字符。
separator 是使用什么隔开。
item 则是代表着集合中的每个元素。

定义好sql即可使用了:

 @Test
    public void selectByIn() {
        List list = new ArrayList();
        list.add(12);
        list.add(23);
        list.add(15);
        list.add(17);
        List<Book> books = this.bookService.selectByIn(list);
        for (Book b : books) {
            System.out.println(b);
        }
    }

当运行时,控制台就会打印出ID为12,23,15,17的书本。

模糊查询

接下来我为大家演示一下三种模糊查询:
Mapper接口:

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

sql:
这里可看到我第一个使用的是#{}、第二个使用的是${}、第三个使用的是concat()函数。后面会为大家讲解这三种区别。

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

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

Test:
大家都知道,模糊查在数据库中是要加入%的。
这里我就写了一个方法来加入:

 public static String toLikestr(String str){
        return "%"+str+"%";
    }

下面来演示:

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

这三种都能输出,第一种和第二种的区别在于第一种会自动加入单引号,第二种不会,这就说明了第二种他是可以进行sql攻击的。比如我在我的参数中加入sql语句,他也是可以执行的。
第三种则不需要自己去加入%,因为在sql中他使用了函数加入进去了。

查询返回结果集的处理

查询返回结果集的处理,也就是sql中的resultType,其实除了resultType还有resultMap。
区别:
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型。比如String、list、int。。。
resultMap:适合使用返回值是自定义实体类的情况。也就是Mapper.xml中定义的:
在这里插入图片描述
然后这两种类型是可以返回5种不同的情况:
1 ,使用resultMap返回自定义类型集合

2, 使用resultType返回List

3,使用resultType返回单个对象

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

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

接口:

这里第三个可以看到我写了一个BookVo类,这个类是干什么用的呢?
vo 是用来存放包括数据库表映射字段以及多余查询条件所需属性
放的也就是和表列不同的参数。例如我要查找 price >14 and price<19
14 和 19 显然不能使用列段参数传递,所以使用Vo

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

// 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
    Map list5(Map map);

Vo类:

package com.zlk.model;

import java.util.List;

public class BookVo extends Book{

    private List<String> bookIds;

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

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

sql:

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

  <select id="list2" resultType="com.zlk.model.Book" >
     select * from t_mvc_book
  </select>

  <select id="list3" resultType="com.zlk.model.Book" parameterType="com.zlk.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() {
//        返回的是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> maps = this.bookService.list4(map);
//        for (Map m : maps) {
//            System.out.println(m);
//        }

//        返回的是resultType 用Map接收
//        Map map = new HashMap();
//        map.put("bid",27);
//        Map map1 = this.bookService.list5(map);
//        System.out.println(map1);
    }

分页查询

为什么要重写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配置拦截器

在Mybatis.cfg.xml中插入:

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

注意的是一定要写在<environments default="development">前面, 不然会报错。

然后在实现接口中写方法:

 @Override
    public List<Map> listPager(Map map, PageBean pageBean) {

        if(pageBean != null && pageBean.isPagination()){
            //使用插件          第一个参数,当前页      第二个参数,偏移量
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        }
        List<Map> maps = this.bookMapper.list4(map);

        if(pageBean != null && pageBean.isPagination()){
            //查看数据
            PageInfo pageInfo = new PageInfo(maps);
            System.out.println("页码:"+pageInfo.getPageNum());
            System.out.println("页大小:"+pageInfo.getPageSize());
            System.out.println("总记录:"+pageInfo.getTotal());
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return maps;
    }

测试:

 @Test
    public void listPager() {
        Map map = new HashMap();
        map.put("bname",StringUtils.toLikestr("圣墟"));
        PageBean pageBean = new PageBean();
        List<Map> maps = this.bookService.listPager(map,pageBean);
        for (Map m : maps) {
            System.out.println(m);
        }
    }

特殊字符处理

值得一提的是,在sql页面中
在这里插入图片描述
若你如图所示写大于或者小于符号,是会报错的,他有专门的方法来表示的。
第一种方法:

&gt; 代替大于 &lt;代替小于

第二种方法:
在sql语句前加上<![CDATA[

后加上 ]]>

<select id="list6" resultType="com.javaxl.model.Book" parameterType="com.javaxl.model.BookVo">
  select * from t_mvc_book
  <where>
    <if test="null != min and min != ''">
      <![CDATA[  and #{min} < price ]]>
    </if>
    <if test="null != max and max != ''">
      <![CDATA[ and #{max} > price ]]>
    </if>
  </where>
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值