英文:
Is there anyway to return value when not found in findby jpa repository
问题
在存储库中创建了一个查询。当未找到值时,我想要响应值。
以下是我的代码:
在存储库中:
Optional<User> findByUsernameAndStatusFalse(String username);
在资源中:
@GetMapping("/user/username/{username}")
public ResponseEntity<User> getUser(@PathVariable String username) {
Optional<User> user = userRepository.findByUsernameAndStatusFalse(username);
return ResponseUtil.wrapOrNotFound(user);
}
英文:
I have create a repository query. I want to response value when not found.
Here are my code:
in repository:
Optional<User> findByUsernameAndStatusFalse(String username);
in resource:
@GetMapping("/user/username/{username}")
public ResponseEntity<User> getUser(@PathVariable String username) {
Optional<User> user = userRepository.findByUsernameAndStatusFalse(username);
return ResponseUtil.wrapOrNotFound(user);
}
答案1
得分: 3
java.util.Optional#orElse
如果可选对象没有值,将返回默认值。示例:
User user = userRepository.findByUsernameAndStatusFalse(username).orElse(null);
英文:
java.util.Optional#orElse
this will return a default value if the optional doesnt have a value. example:
User user = userRepository.findByUsernameAndStatusFalse(username).orElse(null);
答案2
得分: 2
public ResponseEntity
User userExample = new User();
userExample.setUsername(username);
userExample.setStatus(false);
User user = userRepository.findOne(Example.of(userExample)).orElseThrow(
() -> new RuntimeException("用户名未找到:" + username)
);
return ResponseEntity.ok(user);
}
请将此方法添加到控制器
@ExceptionHandler(RuntimeException.class)
public Map<String, Object> handleException(RuntimeException e) {
Map<String, Object> result = new HashMap<>();
result.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
result.put("message", e.getMessage());
return result;
}
当您添加此代码后,如果抛出任何RuntimeException,API将返回状态码500和相应异常的消息。
英文:
You can use :
public ResponseEntity<User> getUser(@PathVariable String username) {
User userExample = new User();
userExample.setUsername(username);
userExample.setStatus(false);
User user = userRepository.findOne(Example.of(userExample)).orElseThrow(
() -> new RuntimeException("Username not found" + username);
);
return ResponseEntity.ok(user);
}
the above code i use findOne and pass an example to search for an object, when not found throws an exception
please add this method to controller
@ExceptionHandler(RuntimeException.class)
public Map<String,Object> handleException(RuntimeException e) {
Map<String,Object> result = new HashMap<>();
result.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
result.put("message", e.getMessage());
return result;
}
When you add this code, all RuntimeException is thrown then api will return status as 500 and message is messgae of that Exception
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论