我尝试使用句柄查询来更新 SQL
数据库中的表。
代码:
@Autowired
private ProducerRepository producerRepository;
public void update(Producer producer){
String name = producer.getProducerName();
long id = producer.getId();
// producerRepository.save(producer); //this method works well.
producerRepository.update(name, id); //handle attempt - throws exeption in this string
}
生产者库:
@Repository
public interface ProducerRepository extends JpaRepository<Producer, Long>{
@Query(nativeQuery = true, value = "UPDATE producer SET producer_name = :pName WHERE id = :id")
Producer update(
@Param("pName") String pName,
@Param("id") long id
);
}
producer
实体的所有参数都是正确的,producerRepository.save(producer)
运行良好。
(我也在控制台 name
和 id
字段中输出 - 好吧)
所以,我可以将 producer
保存在数据库中,但是,当我尝试使用 update()
方法时,我得到了错误。
Can not issue data manipulation statements with executeQuery()
附言
控制台中的sql查询也运行良好
(UPDATE producer SET producer_name = 'some name' WHERE id = ....)
应该注意的是,存储库中的其他 SQL native 查询可以正常工作。所以spring/hibernate/jdbc的设置都是正确的。
最佳答案
使用注解@Modifying
。
This will trigger the query annotated to the method as updating query instead of a selecting one.
来自2.2.6 修改查询 https://docs.spring.io/spring-data/jpa/docs/1.3.4.RELEASE/reference/html/jpa.repositories.html
关于java - Spring Jpa 更新 : Can not issue data manipulation statements with executeQuery(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51249381/