Spring整合MySQL自增ID存储报错问题排查与解决
Spring JPA保存数据到MySQL时SQL语法错误的解决方法
问题场景
在MySQL中创建了一张带自增GROUP_ID的groups表,手动插入数据时自增ID功能正常,但通过Spring JPA保存数据时触发SQL语法错误,报错信息:
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
日志显示错误出现在SQL片段groups (group_icon, group_name, user_id) values (' ', 'abc', 123)附近。
问题原因
groups是MySQL的保留字,直接作为表名使用时,Spring JPA生成的未转义SQL会违反MySQL语法规范,导致执行失败。
解决方法
方案1:修改表名(推荐)
将表名改为非保留字(例如groups_table),同时更新实体类的@Table注解:
@Entity @Data @Table(name="groups_table") public class GroupsEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "GROUP_ID") private int groupId; @Column(name = "GROUP_NAME") private String groupName; @Column(name = "GROUP_ICON") private String groupIcon; @Column(name = "USER_ID") private int userId; }
修改后重新执行保存操作即可正常运行。
方案2:转义保留字表名
若不想修改现有表名,可在@Table注解中给表名添加反引号实现转义:
@Table(name="`groups`")
此方式会让Spring JPA生成带反引号的SQL语句,避免保留字语法冲突。
相关代码片段
服务类
public GroupsResponse setGroups(GroupsRequest request){ int userId = request.getUserId(); GroupsEntity groupsEntity = new GroupsEntity(); groupsEntity.setUserId(userId); groupsEntity.setGroupIcon(request.getGroupIcon()); groupsEntity.setGroupName(request.getGroupName()); GroupsResponse response = new GroupsResponse(); try{ groupsRepository.save(groupsEntity); } catch (Exception e){ log.error("There is an error while saving groups to Groups table. userId: " + userId); response.setStatus(false); response.setMessage(e.getMessage()); return response; } response.setStatus(true); response.setMessage("SUCCESS"); return response; }
仓库类
@Repository public interface GroupsRepository extends JpaRepository<GroupsEntity, Integer> { List<GroupsEntity> findByUserId(int userId); }
请求示例
{ "groupName": "abc", "groupIcon": "", "userId": 123 }
内容的提问来源于stack exchange,提问作者mete ceviz
相关产品推荐
相关产品推荐

