Mybatis的动态sql和分页

Mybatis(2)

前言:Mybatis的动态sql和分页要在完成Mubatis入门搭建下实现

Mybatis动态sql

trim:去空格

<trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="bid != null">
                bid,
            </if>
            <if test="bname != null">
                bname,
            </if>
            <if test="price != null">
                price,
            </if>
 </trim>

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

<if test="bid != null">
                bid,
</if>
<if test="bname != null">
     			bname,
</if>
<if test="price != null">
     			price,
</if>

foreach:遍历集合 批量查询 通常用于in关键字

<select id="selectBooksIn" resultType="com.DZY.model.Book">
      select  * from t_mvc_book where bid in
        <foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
           #{bid}
        </foreach>
  </select>
List<Book> selectBooksIn(@Param("bookIds") List bookIds);

在这里插入图片描述

模糊查询

#{...}

${...}

Concat

注:1) mybatis中使用OGNL表达式传递参数
   2) 优先使用#{...}
   3) #{...}自带引号,${...}有sql注入的风险

BookMapper

    List<Book> selectBooksLike1(@Param("bname")String bname);
    List<Book> selectBooksLike2(@Param("bname")String bname);
    List<Book> selectBooksLike3(@Param("bname")String bname);

BookMapper.xml

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

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

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

BookService

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

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

    @Override
    public List<Book> selectBookLike3(String bname) {
        return bookMapper.selectBookLike3(bname);
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值