Spring Boot中执行原生Insert查询失败求助
解决Spring Boot原生INSERT查询失败的问题
我帮你分析下你遇到的问题,主要是代码里几个细节没处理对,咱们一步步来修正:
问题1:INSERT操作的返回值不合理
原生INSERT语句执行后,并不会返回List<Local>类型的实体列表——插入操作只是往数据库里新增数据,不会做查询返回。你应该把返回值改成int(表示受影响的行数)或者直接用void。
问题2:缺少事务支持
用@Modifying注解做数据修改操作时,必须配合@Transactional注解开启事务,否则大概率会抛出事务相关的异常,导致操作失败。
问题3:参数顺序建议统一
虽然你用了@Param注解指定参数名,SQL和方法参数顺序不匹配也能正常工作,但为了可读性和避免后续出错,最好让方法参数顺序和SQL里的参数顺序保持一致。
修正后的Repository层代码
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import org.springframework.data.jpa.repository.JpaRepository; public interface LocalRepository extends JpaRepository<Local, Long> { @Modifying @Transactional // 必须添加的事务注解 @Query(value = "insert into Local(userId,name,address,pin) VALUES (:userId,:name,:address,:pin)", nativeQuery = true) int insertAttributes(@Param("userId") String userId, @Param("name") String name, @Param("address") String address, @Param("pin") String pin); // 调整参数顺序,返回值改为int }
修正后的Controller层代码示例
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class LocalController { private final LocalRepository localRepository; // 构造注入(推荐的依赖注入方式) public LocalController(LocalRepository localRepository) { this.localRepository = localRepository; } @RequestMapping("insertattributes/{userId}/{name}/{address}/{pin}") public String insertAttributes(@PathVariable String userId, @PathVariable String name, @PathVariable String address, @PathVariable String pin) { int affectedRows = localRepository.insertAttributes(userId, name, address, pin); return "成功插入" + affectedRows + "条数据"; } }
还有几个额外的注意点要提醒你:
- 确认数据库表名是否和SQL里的一致:比如MySQL默认表名是小写,如果你的实体类对应的表是
local,最好在Local实体类上加上@Table(name = "local")来明确指定,避免大小写匹配问题。 - 检查你的数据库连接配置是否正确,确保应用能正常连接到目标数据库。
- 如果你的
Local表主键是自增类型,不需要在INSERT语句中指定主键字段(除非你要手动设置主键值)。
内容的提问来源于stack exchange,提问作者Sr7
相关产品推荐
相关产品推荐

