xxxMapper.xml中编写sql语句时有order by的注意点

项目场景:

项目场景:根据输入的id集合查找数据库中符合的id并按照输入id集合的顺序输出


问题描述:

在编写如下xml语句时


  <select id="selectRank" parameterType="java.util.List" resultType="com.betterlf.myblog.entity.Blog">
            select * from m_blog
            where id in
            <foreach item = "id" collection="cur" open="(" separator="," close=")">
            <!--cur是传入的集合形参名-->
                #{id}
            </foreach>
            order by field (id,
            <foreach item = "id" collection="cur" separator=",">
                #{id}
            </foreach>
            )

        </select>
  • 报错如下:
### Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException:
 Error: Method queryTotal execution error of sql : 
SELECT COUNT(1) FROM m_blog WHERE id IN (?) 
  • 问题:
    为什么 in 后面的order by等语句没有显示?

原因分析:

#{}占位符不能解决一下 3 类问题:
表名是动态的: Select * from #{table_name}
列名是动态的:Select #{column_name} from t_role
排序列是动态的: Select * from t_role order by #{columu}

而${}方式一般用于传入数据库对象,比如这种group by 字段 ,order by 字段,
表名,字段名等没法使用占位符的就需要使用${param}

解决方案:

- 将order by field后要加的id参数用${}代替#{}

  <select id="selectRank" parameterType="java.util.List" resultType="com.betterlf.myblog.entity.Blog">
            select * from m_blog
            where id in
            <foreach item = "id" collection="cur" open="(" separator="," close=")">
            <!--cur是传入的集合形参名-->
                #{id}
            </foreach>
            order by field (id,
            <foreach item = "id" collection="cur" separator=",">
                ${id}
            </foreach>
            )

        </select>
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值