简体   繁体   中英

why I am getting error as unexpected token

I am trying to update employee salary by using this query. Why I am getting unexpected token:near line 1 in JPA Query error.


 @Query("update employee set sal=  sal + 2000  where salary < :sal")
 void updateEmployeeSalary(@Param("sal") Long sal)

And this is my service method


 List<Employee> updateSalary(Long sal){
   repo.updateEmployeeSalary(sal);
   return repo.findAll();
 }

You need the @Modifying annotation :

@Modifying
@Query("update employee set sal=  sal + 2000  where salary < :sal")
 void updateEmployeeSalary(@Param("sal") Long sal)

If you want to perform Update and Delete operation in Spring Boot JPA operation you want to declare @Modifying annotation

Why declare @Modifying annotation -> To enhance the @Query annotation to execute not only SELECT queries but also INSERT, UPDATE, DELETE, and even DDL queries

What if we forget to declare @Modifiying annotation -> Compiler throw exception InvalidDataAccessApiUsageException means query is not supported for DML operations.

clearAutomatically=true defines whether we should clear the underlying persistence context after executing the modifying query

Modified Repository:

@Modifying(clearAutomatically=true)
@query("update Employee set salary = salary + 2000 where salary< :sal")

I think you need to write a query like this

@Modifying
@query("update Employee e set e.salary = e.salary+2000 where e.salary< :sal")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM