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

本文详细介绍了MyBatis的动态SQL,包括if、trim和foreach的使用,以及模糊查询和分页查询的实现。在模糊查询中对比了#与$的区别,强调了防止SQL注入的重要性。对于分页查询,说明了MyBatis原生分页的不足,并展示了如何使用分页插件PageHelper进行有效分页。最后,讨论了在XML配置中处理特殊字符的方法。
摘要由CSDN通过智能技术生成

mybaits动态sql

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

 <if test="bname != null" >
        #{bname,jdbcType=VARCHAR},
      </if>

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<Book> bb = this.bookService.selectBylike2(StringUtils.toLikeStr("圣墟"));
//        List<Book> bb = this.bookService.selectBylike3(StringUtils.toLikeStr("圣墟"));

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

在这里插入图片描述

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. 一般能用#的就别用$.
    在这里插入图片描述

查询返回结果集的处理

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

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

  <resultMap id="BaseResultMap" type="com.cpc.model.User" >
    <constructor >
      <idArg column="id" jdbcType="INTEGER" javaType=
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值