欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > Java 使用MyBatis-Plus数据操作关键字冲突报错You have an error in your SQL syntax问题

Java 使用MyBatis-Plus数据操作关键字冲突报错You have an error in your SQL syntax问题

2025/2/24 15:15:16 来源:https://blog.csdn.net/qq_33789001/article/details/143772725  浏览:    关键词:Java 使用MyBatis-Plus数据操作关键字冲突报错You have an error in your SQL syntax问题

问题

这个报错是出现在Java Spring boot项目中,使用MyBatis-Plus通过创建的实体类对数据库的操作过程中,通过实体创建数据库表是没有问题的,而在接口调用服务类操作数据库的时候,会出现报错。报错详情如下:

服务请求异常:org.springframework.jdbc.BadSqlGrammarException:
com..server.mapper.UsageMapper.insert (batch index #1) failed.
Cause: java.sql.BatchUpdateException: 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 'usage,…
… create_time,
update_time) VALUES (1854720160046714882, 18547201’ at line 1; bad
SQL grammar []; nested exception is java.sql.BatchUpdateException: 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 'usage,
… , create_time, update_time) VALUES (1854720160046714882,
18547201’ at line 1.
在这里插入图片描述

其中的实体类如下:

@Data
@TableName(autoResultMap = true)
@TableComment("用量信息")
@ApiModel(value = "用量信息")
public class GoodsUsage {@ApiModelProperty(value = "id")@Column(comment = "id")private Long id;@ApiModelProperty(value = "用量")@Column(comment = "用量")private BigDecimal usage;@ApiModelProperty("创建时间")@Column(comment = "创建时间")private LocalDateTime createTime;@ApiModelProperty("更新时间")@Column(comment = "更新时间")private LocalDateTime updateTime;
}

报错的调用处理是批量保存数据记录:

this.saveBatch(usages);

解决方法

看到报错问题,以为是关键字引起数据库操作问题,后来发现MyBatis-Plus已经根据实体创建出了数据库表:
在这里插入图片描述

后续没有照着这个方向调试,而是以为MyBatis-Plus 的LambdaQueryWrapper 表达式所生成的SQL语句有问题,排查了很久,也没有发现问题,不过将控制台选择复制打印的params的sql语句复制过去存在同样的报错,最后发现是usage字段名和MySQL的Usage权限重名了,也就是关键字冲突,将usage字段重命名为其他可用的名称即可修复。

以下为其他解决参考:
注意尽量避免使用关键字作为表名或者字段名,如果一定要用关键字作为字段名,在SQL处理时,用单引号将名称括起来(‘usage’); MyBatis-Plus 的关键字处理,可以使用 @TableName 和 @TableField 注解来处理关键字,这样 MyBatis-Plus 在构建 SQL 时会使用单引号‘’来包围列名,从而避免了关键字冲突。
可以使用如下代码获取所有保留关键字:

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.SqlReservedWords;String keywords = String.join(StringPool.COMMA, SqlReservedWords.KEYWORDS);
System.out.println("保留关键字: " + keywords);

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com