本文已参与「新人创作礼」活动,一起开启掘金创作之路。
- 微信公众号关注:SteveCode。为您分享更多的知识学术。生于忧患死于安乐
为什么会报错,是为什么 【已解决】
看代码
web
@GetMapping("selectUserByInName")
@ApiOperation("多个用户名查用户")
public List<User> selectUserByInName() {
List<String> names = new ArrayList<>();
// names.add("胎菊");
// names.add("小石");
return userService.selectUserByInName(names);
}
mybaits.xml
<select id="selectUserByInName" resultType="com.huatech.entity.User">
select * from shop_user where
<if test="names !=null">
username in
<foreach collection="names" index="index" open = '(' separator = ',' close = ')' item="item">
#{item}
</foreach>
</if>
</select>
以上的传参方式会报:
select * from shop_user where username in 重要是这条sql
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3] with root cause
那条sql竟然没有 () in后面不就应该由() 不好意思 控制台上就是没有。
为什么
<select id="selectUserByInName" resultType="com.huatech.entity.User">
select * from shop_user where
<if test="names !=null"> 这一层校验过了(传过来的是空集合)
username in
<foreach collection="names" index="index" open = '(' separator = ',' close = ')' item="item">
(下面这个循环在解析时他是空集合)
#{item}
</foreach>
</if>
</select>
所以控制台打印sql语法错误:
select * from shop_user where username in 错误的语法
如何解决:
<select id="selectUserByInName" resultType="com.huatech.entity.User">
select * from shop_user where
<if test="names !=null and names.size>0">
双重校验 1:是不是null
2:这个集合大小是不是>0
username in
<foreach collection="names" index="index" open = '(' separator = ',' close = ')' item="item">
#{item}
</foreach>
</if>
</select>
补充 加一个where标签
<select id="selectUserByInName" resultType="com.huatech.entity.User">
select * from shop_user
<where>
<if test="names !=null and names.size>0">
and username in
<foreach collection="names" index="index" open = '(' separator = ',' close = ')' item="item">
#{item}
</foreach>
</if>
</where>
</select>
线上bug:后台xshell一直报sql异常。今天在此复测-解决 2021-07-23-20:39
mybatis动态sql if test 传过来是个集合ids怎么解析它 为什么 这么写【问题解决】在此记录