2017-05-25 72 views
0

我想從我的數據庫中刪除一些員工 但我不能。 這是我的倉庫代碼:在春季項目刪除JpaRepository

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" 

}

+0

可以更改數據的查詢[需要使用@ @修飾]註釋(https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.modifying-queries)和'@ Transactional'。 – manish

回答

1

使用Spring數據JPA ,您只能在默認情況下檢索/插入新記錄。因此,如果您想修改/更新/刪除現有記錄,則必須將您的方法標記爲@Transactional & @修改以指示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); 
} 
+0

它可能在工作 但我得到另一個錯誤,因爲「employees」的ID是另一個表中的外鍵 message:無法刪除或更新父行:外鍵約束失敗('t_anomalies'.'traitement',CONSTRAINT 'FKafuchse28bfyo9jy5cgxqlybx' FOREIGN KEY('id_employe')REFERENCES'employe'('id_employe')) – hich

+0

@在這種情況下,首先必須刪除它的子記錄,如上面的情況,它的'message'表,然後是父記錄'僱員' – Afridi

0

您使用的是JpaRepository,那麼你已經在你的儲存庫delete由ID)方法。你爲什麼要實現另一個?

如果需要,Spring Boot應自動爲您的存儲庫設置事務設置,因此您無需設置它們。