项目是springboot+mybatis,由于查询需要动态select,如下图
@Select("<script>" +
"select *from recruit" +
"<where>" +
"<if test='recruit_type!=0'>AND recruit_type=#{recruit_type}</if>" +
"<if test='work_type!=0'>AND work_type=#{work_type}</if>" +
"<if test='work_city!=0'>AND work_city=#{work_city}</if>" +
"</where>" +
"</script>")
List<Recruit> selectRecruit(@Param("recruit_type") int recruit_type, @Param("work_type") int work_type, @Param("work_city") int work_city);
函数传入没问题,测试时一直报错
### The error occurred while setting parameters
### SQL: select *from recruit WHERE recruit_type=?AND work_type=?
### Cause: 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 'work_type=3' at line 1
把查询语句换成具体的数值测试。
@Select("<script>" +
"select *from recruit" +
"<where>" +
"<if test='recruit_type!=0'>AND recruit_type=1</if>" +
"<if test='work_type!=0'>AND work_type=1</if>" +
"<if test='work_city!=0'>AND work_city=1}</if>" +
"</where>" +
"</script>")
List<Recruit> selectRecruit(@Param("recruit_type") int recruit_type, @Param("work_type") int work_type, @Param("work_city") int work_city);
还是一样报错
### The error occurred while setting parameters
### SQL: select *from recruit WHERE recruit_type=1AND work_type=1
### Cause: 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 'work_type=1' at line 1
把SQL语句放到数据库里测试,发现and连接词和前面的数值连在一起了!
加入空格后测试正常。因此在每个if查询加个空格就可以解决问题了。