在Spring项目中删除JpaRepository

时间:2017-05-25 05:14:55

标签: spring-mvc spring-boot

我试图从我的数据库中删除一些员工 但我不能。 这是我的存储库代码:

public interface EmployeRepository extends JpaRepository<Employe, Long> {
@Query("delete from Employe e where e.idEmploye=:x")
public Employe deleteEmploye(@Param("x") int idEmploye); }

这是我的控制器:

@RestController public class EmployeRestService {
@Autowired
private EmployeMetier EmployeMetier;
@RequestMapping(value="/employe3",method=RequestMethod.DELETE)
public Employe deleteEmploye(@RequestParam int idEmploye) {
    return EmployeMetier.deleteEmploye(idEmploye);}}

当我测试我的控制器时,我收到此消息

{"timestamp": 1495688812536,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "org.hibernate.hql.internal.QueryExecutionRequestException: Not 
supported for DML operations [delete from org.st.entities.Employe e where 
e.idEmploye=:x]; nested exception is java.lang.IllegalStateException: 
org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for 
DML operations [delete from org.st.entities.Employe e where 
e.idEmploye=:x]",
"path": "/employe3"

}

1 个答案:

答案 0 :(得分:1)

使用Spring Data JPa,您只能默认检索/插入新记录。因此,如果您想修改/更新/删除现有记录,则必须将您的方法标记为@Transactional&amp; @Modifying指示Spring给定的方法可以随时改变现有记录。所以 试试这个:

public interface EmployeRepository extends JpaRepository<Employe, Long> {

    @Transactional
    @Modifying
    @Query("delete from Employe e where e.idEmploye=:x")
    public Employe deleteEmploye(@Param("x") int idEmploye); 
}