春季:无法使用executeQuery()发出数据操作语句

时间:2018-07-09 15:43:44

标签: java mysql spring spring-jdbc

我尝试使用句柄查询来更新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
    }

ProducerRepository:

@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)运行良好。 (也是我在控制台nameid字段中-好的)

因此,我可以将producer保存在数据库中,但是,当我尝试使用update()方法时,会收到错误消息。

  

无法使用executeQuery()发出数据操作语句


PS

控制台中的

sql查询也很好

(UPDATE producer SET producer_name = 'some name' WHERE id = ....)

应注意,存储库中的其他SQL本机查询正常运行。因此spring / hibernate / jdbc设置正确。

3 个答案:

答案 0 :(得分:5)

使用注释@Modifying

  

这将触发注释为方法的查询作为更新查询   而不是选择一个。

来自 2.2.6修改查询 https://docs.spring.io/spring-data/jpa/docs/1.3.4.RELEASE/reference/html/jpa.repositories.html

答案 1 :(得分:1)

如果上述解决方案不起作用,请使用此

@Modifying
    @Transactional 
    @Query(value ="delete from admindata where user_name = :userName AND group_name = :groupName",nativeQuery = true)
    public void deleteadminUser(@Param("userName") String userName,@Param("groupName") String groupName);

答案 2 :(得分:0)

@Query(nativeQuery = true, value = "UPDATE producer SET producer_name = :pName WHERE id = :id") 生产者更新( @Param("pName") 字符串 pName, @Param("id") 长 id );

您的更新方法正在返回生产者对象,返回应该是 int 或 void,因为您正在返回生产者实体,Spring JPA 认为它必须获取对象而不是更新它,这就是它正在执行的原因executeQuery,而不是executeUpdate,您还需要@Modifying 注解。

相关问题