Although this situation is easy for ready overrided methods, I couldn’t find a way for my own query.
This is my repository :
public interface CommentRepository extends JpaRepository<User , Long >{
@Modifying
@Transactional
@Query( value="delete from users where first_name=:name" , nativeQuery=true )
public void delete( String name );
}
This is my controller :
@RestController
@RequestMapping(path="/api/v1/users")
public class CommentController {
@Autowired
CommentRepository repository ;
// Delete user
@DeleteMapping(path="/delete")
public void delete(@RequestParam String name) {
repository.delete(name) ;
}
}
For example, if I delete a user, I want to pass a status code of 200 to the developer if the query is successful.
However I want to pass different codes if the query fails.
2
Answers
ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response.
Have a look at Response entity using which you will be able to configure everything including status codes .
https://www.baeldung.com/spring-response-entity
In the rest controller you can do something like:
Since I don’t know your database structure, let’s say a
SQLIntegrityConstraintViolationException
can be thrown, you can create a service layer that will handle the exception. You will end up with something like:Then you have lots of ways to handle your new exception. Please read more here: https://www.baeldung.com/exception-handling-for-rest-with-spring
One of the ways is to have this inside your @RestController class
for the last part you can play around with the exceptions thrown on the service layer and return appropriate status code from the corresponding exception handler. Consider having a global exception handler as stated into the article on Baeldung above. Hope it helps a little bit.