java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > MyBatis SQL语法错误

MyBatis SQL语法错误:缺少LIKE关键字详解与解决方案

作者:步行cgn

在MyBatis模糊查询中遇到SQLSyntaxErrorException错误,本文详细分析brand concat('%',?,'%')报错的原因,指出缺少LIKE关键字的问题,并提供三种解决方案和完整示例,帮助你快速修复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 'concat('%','宝马','%')' at line 2

执行 SQL(从日志中截取):

select id, car_num, brand, guide_price, produce_time, car_type 
from t_car                                                                  
where brand concat('%', ?, '%')

参数:宝马(String)

二、错误含义

这条 SQL 的 WHERE 子句中,brand 后面直接跟了 concat('%',?, '%'),但 MySQL 中模糊匹配必须使用 LIKE 关键字,不能直接将表达式放在列名后面。

也就是说,brand concat(...) 是非法的 SQL 语法,正确的写法应当是 brand LIKE concat(...)。

三、错误代码示例

你的 CarMapper.xml 中很可能写了类似:

<select id="selectCar" resultType="com.xie.entity.Car">
    select id, car_num, brand, guide_price, produce_time, car_type 
    from t_car
    where brand concat('%', #{brand}, '%')
</select>

或者可能是:

<select id="selectCar" resultType="com.xie.entity.Car">
    select id, car_num, brand, guide_price, produce_time, car_type 
    from t_car
    where brand concat('%', '${brand}', '%')
</select>

但无论哪种,都缺少了 LIKE 关键字。

四、解决方案

方案一:直接加上LIKE(推荐)

<select id="selectCar" resultType="com.xie.entity.Car">
    select id, car_num, brand, guide_price, produce_time, car_type 
    from t_car
    where brand LIKE concat('%', #{brand}, '%')
</select>

使用 #{} 可以安全地防止 SQL 注入。

方案二:使用bind标签(另一种写法)

<select id="selectCar" resultType="com.xie.entity.Car">
    <bind name="pattern" value="'%' + brand + '%'"/>
    select id, car_num, brand, guide_price, produce_time, car_type 
    from t_car
    where brand LIKE #{pattern}
</select>

方案三:在 Java 代码中拼接%

// Mapper 接口
List<Car> selectCar(@Param("brand") String brand);

// 调用时
String brand = "宝马";
carMapper.selectCar("%" + brand + "%");

XML 中:

<select id="selectCar" resultType="com.xie.entity.Car">
    select id, car_num, brand, guide_price, produce_time, car_type 
    from t_car
    where brand LIKE #{brand}
</select>

这种方式将拼接逻辑移到 Java 层,XML 更简洁。

五、错误原因分析

从日志 ==> Preparing: ... where brand concat('%',?,'%') 可以看出,MyBatis 生成的 SQL 中,concat 函数直接被放在了 brand 后面,而没有 LIKE。这说明 XML 中漏写了 LIKE。

这是典型的 SQL 语法错误,与 MyBatis 参数绑定无关。

六、修正后的完整示例

Mapper 接口:

List<Car> selectCar(@Param("brand") String brand);

XML 映射:

<select id="selectCar" resultType="com.xie.entity.Car">
    select id, car_num, brand, guide_price, produce_time, car_type 
    from t_car
    where brand LIKE concat('%', #{brand}, '%')
</select>

测试代码:

List<Car> cars = carMapper.selectCar("宝马");
cars.forEach(System.out::println);

七、总结

错误类型原因解决方案
SQLSyntaxErrorException near concat(...)WHERE 子句中缺少 LIKE 关键字在列名和条件表达式之间加上 LIKE

记住:MySQL 的模糊查询必须使用 LIKE 关键字,格式为 column LIKE pattern,不能省略。

以上就是MyBatis SQL语法错误:缺少LIKE关键字详解与解决方案的详细内容,更多关于MyBatis SQL语法错误的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文