mybatis注解sql <script></script> 报错提示:元素内容必须由格式正确的字符数据或标记组成

mybatis在使用标签时,{<、>、<=、>=}等符号需要转译否则不认报错;

原符号

<<=>>=&、 '、 "、

替换符号

\&lt;、 \&lt;=、 \&gt;、 \&gt;=、 \&amp;、 \&apos;、 \&quot;

例如:sql如下:
create_date_time &gt;= #{startTime} and create_date_time &lt;= #{endTime}

注意:if 标签内判断 0 ,1等数字时,不需要加引号

"<script>" +
            "SELECT " +
            "id,name " +
            "FROM user_info" +
            "WHERE " +
            " isdelete = '0'" +
            " <if test=\" type != null and type!= 0 \"> AND type = #{type} </if> "+
             "</script>"
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现 List<User> getUsersByIds(@Param("ids") String ids) 方法,可以使用 MyBatis 中的 foreach 标签来实现。具体实现步骤如下: 1. 在 SQL 语句中使用 foreach 标签,循环遍历传入的 ids 参数,生成一个 IN 子句,查询多个 id 对应的用户信息。SQL 语句如下: ``` SELECT * FROM user WHERE id IN <foreach item='id' index='index' collection='ids' open='(' separator=',' close=')'> #{id} </foreach> ``` 2. 在接口方法上使用 @Select 注解,指定 SQL 语句。代码如下: ``` @Select("SELECT * FROM user WHERE id IN\n" + "<foreach item='id' index='index' collection='ids' open='(' separator=',' close=')'>\n" + " #{id}\n" + "</foreach>") List<User> getUsersByIds(@Param("ids") String ids); ``` 3. 在调用方法时,传入一个以逗号分隔的 id 字符串,如 "1,2,3",然后将其转换为一个列表,传入 getUsersByIds 方法中。代码如下: ``` List<User> users = getUsersByIds("1,2,3"); ``` 这样就可以根据传入的 id 列表查询对应的用户信息了。注意,如果传入的 id 列表为空,生成的 SQL 语句会变成 "SELECT * FROM user WHERE id IN()",这样会导致 SQL 语法误,需要在 foreach 标签中添加一个判断,如果传入的列表为空,则返回一个空的 IN 子句。具体可以参考下面的代码: ``` @Select("<script>SELECT * FROM user WHERE 1=1\n" + "<if test=\"ids != null and ids != ''\">\n" + " AND id IN\n" + " <foreach item='id' index='index' collection='ids.split(\",\")' open='(' separator=',' close=')'>\n" + " #{id}\n" + " </foreach>\n" + "</if>\n" + "</script>") List<User> getUsersByIds(@Param("ids") String ids); ``` 这样就可以根据传入的 id 列表查询对应的用户信息了,而且还可以处理传入的 id 列表为空的情况。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值