【问题标题】:Running a native insert query in spring boot在 Spring Boot 中运行本机插入查询
【发布时间】:2018-09-16 02:29:57
【问题描述】:

我正在尝试在 Spring Boot 中运行一个简单的插入查询,但我无法这样做。

查询:

@Modifying
    @Query(value = "insert into Local(userId,name,address,pin) VALUES (:userId,:name,:address,:pin)", nativeQuery = true)

    List < Local > insertattributes(@Param("userId")String userId,@Param("address") String address ,@Param("name")String name,@Param("pin") String pin);

控制器:

@RequestMapping("insertattributes/{userId}/{name}/{address}/{pin}")
    @ResponseBody
    public List < Local > insertAttributes(@PathVariable String userId, @PathVariable String name, @PathVariable String address, @PathVariable String pin) {

        return localService.insertattributes(userId,name,address,pin);
    }

错误:

o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: S1009
o.h.engine.jdbc.spi.SqlExceptionHelper   : Can not issue data manipulation statements with executeQuery().
[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause

java.sql.SQLException: Can not issue data manipulation statements with executeQuery().

【问题讨论】:

  • 您在存储库中的insertattributes 方法应该是void。在插入期间期望List&lt;Local&gt; 是不合适的
  • 我想缓存响应。这就是我试图返回列表的原因。

标签: spring-boot spring-data-jpa hibernate-native-query


【解决方案1】:

插入语句不返回插入的记录。由于您期望返回列表 executeQuery() 由 Spring 执行。你想要的是 executeUpdate() 的执行g,它只对 void 方法执行。

另见Cannot issue data manipulation statements with executeQuery()

【讨论】:

  • 有没有办法获取列表?
  • 我在更新查询中也发现了同样的问题。我明白你在说什么,但是否有解决方法以便我可以获取列表或对象?
  • 这里的问题是你真正想要做什么。是否需要为您的插入执行本机查询?为什么不创建Local 类的实例并在JpaRepository 中调用repository.save()?这也会为您返回保存的记录。另请参阅spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa 以供参考
猜你喜欢
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2022-01-05
  • 1970-01-01
  • 2018-11-12
  • 2019-12-18
相关资源
最近更新 更多