Search code examples
javahibernatespring-data-jpanativequery

Native Query INSERT is giving ERROR : Method is only allowed for a Query


I am currently working on a SpringBoot + Hibernate project. I have a requirement to Insert few values to a DB.

I am trying to achieve this using Native Query. Below is my Code :

@Repository
public interface StoreDataRepository extends JpaRepository<StoreDataRepository, Long> {

    @Query(value ="insert into store (id, name) values(:id, :name)", nativeQuery = true)
    public void storeData(@Param("id") int id, @Param("name") String name);

From my Service, I am just calling this method with id and name parameters.

But I am getting the below error :

org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Method only for queries

Can you please assist me with this ?


Solution

  • I was able to fix the above issue.

    I had to specify @Transactional and @Modifying to my Repository method.

    Below solved the issue.

    @Repository
    public interface StoreDataRepository extends JpaRepository<StoreDataRepository, Long> {
    
        @Trsansactional
        @Modifying
        @Query(value ="insert into store (id, name) values(:id, :name)", nativeQuery = true)
        public void storeData(@Param("id") int id, @Param("name") String name);