2

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 ?

Scarlett John
  • 99
  • 1
  • 11
  • 1
    If using Spring, add `@Modifying` as documented here: [Spring Data JPA - Reference Documentation - 4.3.8. Modifying queries](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.modifying-queries) – Andreas Mar 14 '18 at 01:44
  • Hi Andreas - Yes I tried using the @Modifying but then I get an error such as : javax.persistence.TransactioRequiedException: Executing an update/delete query – Scarlett John Mar 14 '18 at 02:06
  • 1
    So why aren't you in a transaction when doing updates? – Andreas Mar 14 '18 at 02:17

1 Answers1

5

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);
Scarlett John
  • 99
  • 1
  • 11