【问题标题】:why I am getting error as unexpected token为什么我收到错误作为意外令牌
【发布时间】:2021-10-30 03:51:38
【问题描述】:
我正在尝试使用此查询更新员工工资。为什么我收到unexpected token:near line 1 in JPA Query 错误。
@Query("update employee set sal= sal + 2000 where salary < :sal")
void updateEmployeeSalary(@Param("sal") Long sal)
这是我的服务方法
List<Employee> updateSalary(Long sal){
repo.updateEmployeeSalary(sal);
return repo.findAll();
}
【问题讨论】:
标签:
java
spring
spring-boot
hibernate
【解决方案1】:
你需要@Modifying annotation:
@Modifying
@Query("update employee set sal= sal + 2000 where salary < :sal")
void updateEmployeeSalary(@Param("sal") Long sal)
【解决方案2】:
如果你想在Spring Boot JPA操作中执行Update和Delete操作你要声明@Modifying注解
为什么要声明@Modifying注解->
增强@Query 注解,不仅可以执行 SELECT 查询,还可以执行 INSERT、UPDATE、DELETE 甚至 DDL 查询
如果我们忘记声明@Modifiying 注释怎么办 ->
编译器抛出异常InvalidDataAccessApiUsageException 表示DML 操作不支持查询。
clearAutomatically=true 定义我们是否应该在执行修改查询后清除底层持久化上下文
修改后的存储库:
@Modifying(clearAutomatically=true)
@query("update Employee set salary = salary + 2000 where salary< :sal")
【解决方案3】:
我认为您需要编写这样的查询
@Modifying
@query("update Employee e set e.salary = e.salary+2000 where e.salary< :sal")