繁体   English   中英

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

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

尽管这种情况对于现成的重写方法很容易,但我找不到自己查询的方法。

这是我的存储库:

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 );
}

这是我的 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) ;
    }
}

例如,如果我删除一个用户,如果查询成功,我想将状态码 200 传递给开发人员。

但是,如果查询失败,我想传递不同的代码。

ResponseEntity 代表整个 HTTP 响应:状态码、标头和正文。 因此,我们可以使用它来完全配置 HTTP 响应。

查看响应实体,您可以使用它来配置包括状态代码在内的所有内容。

https://www.baeldung.com/spring-response-entity

在 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();
    }
}

由于我不知道您的数据库结构,假设可以抛出SQLIntegrityConstraintViolationException ,您可以创建一个服务层来处理该异常。 你最终会得到类似的东西:

@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
   }

}

然后你有很多方法来处理你的新异常。 请在此处阅读更多信息: https://www.baeldung.com/exception-handling-for-rest-with-spring

一种方法是在你的@RestController class

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

对于最后一部分,您可以处理服务层上抛出的异常,并从相应的异常处理程序返回适当的状态代码。 考虑使用上面关于 Baeldung 的文章中所述的全局异常处理程序。 希望它有一点帮助。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM