Search code examples
javajpaspring-data-jpajpql

How to make insert custom query in spring data jpa by using @Query annotation


I am using mssql and spring data JPA, I want to insert new records to a table by using custom @Query annotation.

public interface CustomerRepository extends JpaRepository<Customers, String>{


    @Modifying
    @Query("insert into Customers values (?1 , ?2)")
    public void saveCutomer(int custId, Customer cust);

}

Its giving error,

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting OPEN, found 'values' near line 1, column 23 [insert into Customers values (?1 , ?2)]

I tried below also, same error.

@Modifying
    @Query("insert into Customers select ?1 , ?2")
    public void saveCutomer(int custId, Customer cust);

Solution

  • You don't do that using JPQL. You have batch DELETE and UPDATE but that's it.

    Your options are:

    1) Mark the query as native if you really make explicit insert (not recommended unless you intend to use some database-specific syntax not supported by JPQL.

    2) Use standard save(Entity) method on your repository which is of course preferable.