简体   繁体   English

如果Spring启动查询成功,我想发送一个状态码,我该怎么做?

[英]I want to transmit a status code if the query is successful with Spring boot, how can I do it?

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:这是我的 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.例如,如果我删除一个用户,如果查询成功,我想将状态码 200 传递给开发人员。

However I want to pass different codes if the query fails.但是,如果查询失败,我想传递不同的代码。

ResponseEntity represents the whole HTTP response: status code, headers, and body. ResponseEntity 代表整个 HTTP 响应:状态码、标头和正文。 As a result, we can use it to fully configure the HTTP response.因此,我们可以使用它来完全配置 HTTP 响应。

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 https://www.baeldung.com/spring-response-entity

In the rest controller you can do something like:在 rest controller 中,您可以执行以下操作:

@RestController
@RequestMapping(path="/api/v1/users")
public class CommentController {
    
    @Autowired
    CommentRepository repository ;
    
    // Delete user
    
    @DeleteMapping(path="/delete")
    public ResponseEntity<Void> delete(@RequestParam String name) {
        
        repository.delete(name);
        return ResponseEntity.ok().build();
    }
}

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.由于我不知道您的数据库结构,假设可以抛出SQLIntegrityConstraintViolationException ,您可以创建一个服务层来处理该异常。 You will end up with something like:你最终会得到类似的东西:

@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {
  
   private final CommentRepository commentRepository;

   @Override
   public void deleteUsersByName(String name) {
     try {
         commentRepository.delete(name); //consider changing the repo method name 'delete' to be more contextual like 'deleteAllByName(String name)'
     } catch (Exception | SQLIntegrityConstraintViolationException e) //or other type, depending on your database structure
       throw new MyCustomException("my message: " + e); //create new RuntimeException with the name you prefer
   }

}

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请在此处阅读更多信息: https://www.baeldung.com/exception-handling-for-rest-with-spring

One of the ways is to have this inside your @RestController class一种方法是在你的@RestController class

@ExceptionHandler({MyCustomException.class})
    public ResponseEntity<Void> handleConstrainViolationException() {
        return ResponseEntity.internalServerError(); //just an example
    }

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.考虑使用上面关于 Baeldung 的文章中所述的全局异常处理程序。 Hope it helps a little bit.希望它有一点帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Spring Boot 返回成功消息? - How can I return a successful message using Spring Boot? 如何使用 Boot 仅更改 Spring MVC 错误上的状态代码? - How do I change only the status code on a Spring MVC error with Boot? 如何将此代码从Spring转换为Spring Boot? - How do I convert this code from Spring to Spring Boot? 基于参数/条件的值,我想在类中注入依赖项。 我如何在春季靴中做到这一点? - Based on a value of a parameter/condition I want to inject a dependency in my class. How can I do that in spring boot? 如何在 Spring Boot 控制器中检索查询参数? - How do I retrieve query parameters in a Spring Boot controller? 如何在 Spring Boot 的查询注释中使用我的参数? - How can I use my parameter in query annotation in Spring Boot? 如何使用 Spring 引导在 JPA 存储库中编写 SQL 查询? - How can I write SQL query in JPA repository with Spring Boot? 如何在带有 Spring Boot 的本机查询中使用 all(array[])? - How can I use all(array[]) in a native query with Spring Boot? 如何减少弹簧启动控制器中的重复代码 - How can i reduce repetitive code in spring boot controllers 如何通过运行 spring 启动测试代码解决此问题? - How can I solve this problem with run spring boot test code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM