2016-08-30 197 views
3

我正在爲大學項目編寫一個簡單的庫API。我有一個帶書籍的數據庫,每個都有自己的ID。我正在使用Spring Boot來提供服務。我有一個BookRepository,它擴展了JpaRepository<Book, Long>和服務實現。JPA EmptyResultDataAccessException處理

@Service 
public class BookServiceImpl implements BookService{ 

    @Autowired 
    private BookRepository bookRepository; 

    @Async 
    @Override 
    public void delete (Long id){ 
     bookRepository.delete(id); 
    } 
} 

稍後,一個REST控制器處理該請求:

@RestController 
public class BookServiceController{ 

    @Autowired 
    private BookService bookService; 

    @RequestMapping(value="books/{id}", method = RequestMethod.DELETE) 
    public ResponseEntity<Book> deleteBook (@PathVariable("id") Long id){ 
     bookService.delete(id); 
     return new ResponseEntity<Book>(HttpStatus.OK); 
    } 
} 

現在,如果我要刪除一本書,其是未在數據庫中,例如具有123中的ID,I」 d得到一個EmptyResultDataAccessException拋出。

我的問題是,我如何以及在哪裏處理異常,以及如何避免以這種方式投射NullPointerException?

在此先感謝。

+0

(1)是否有一個原因,你在存儲庫上分層單獨的'BookService'? (2)儘可能優先考慮構造函數注入到字段注入。 – chrylis

回答

1

對於DELETE操作,您不再真正返回實體;你只是確認資源已經消失。由於DELETE是冪等的(可以多次刪除記錄),因此無論記錄是否存在,您都可以返回相同的狀態碼,如果找不到記錄,則返回404。您還可以簡化處理方法:

@DeleteMapping("/books/{id}") 
@ResponseStatus(HttpStatus.NO_CONTENT) // because you deleted it 
public void deleteBook(@PathVariable Long id) { 
    try { 
     bookService.delete(id); // or just use the repository directly 
    } catch (EmptyResultDataAccessException ex) { 
     // either do nothing to return a 204, or 
     throw new NotFoundException(); 
    } 
} 

,你有一個例外,指示狀態:

@ResponseStatus(HttpStatus.NOT_FOUND) 
public class NotFoundException extends RuntimeException {} 

這是合理的,應該EmptyResultDataAccessException已經NOT_FOUND狀態來註解;這是一個潛在的增強請求。

+0

我試過這個,並且無論如何都會返回EmptyResultDataAccessException。 – Flopn