返回 Hibernate 唯一结果的最简洁方法是null什么?
这个解决方案有什么问题吗:
public Category getCategoryById(int id) {
Object result = currentSession.createCriteria(Category.class)...uniqueResult();
return (Category) result;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
没有干净的方法可以做到这一点,因为这取决于您的 API。
如果您表示您的方法可以返回null,特别是在 JavaDoc 中 - 可能受 a 支持@Nullable,那么这里返回没有任何问题null。
如果我期望所请求的值在我的应用程序中不存在于某些有效状态,我通常会这样做:
/**
* Tries to find a category by its id.
*
* @param id the id
* @return the category for that id or {@code null} if not found
*/
@Nullable
public Category findCategoryById(int id) {
Object result = ....uniqueResult();
return (Category) result;
}
Run Code Online (Sandbox Code Playgroud)
另一方面,如果缺少的元素无效,您可以抛出异常并记录该异常:
/**
* Resolve a category by its id.
*
* @param id the id as given by another method
* @return the category for that id
* @throws NoSuchElementException if the element does not exist
*/
@Nonnull
public Category getCategoryById(int id) {
Object result = ....uniqueResult();
if (result == null) {
throw new NoSuchElementException("category for id: " + id);
}
return (Category) result;
}
Run Code Online (Sandbox Code Playgroud)
(我必须承认我只是偶尔使用注释)
我在这两种情况下使用不同的方法名称(findCategoryByIdvs getCategoryById)。如果您坚持命名方案,您的 API 的用户无需阅读 JavaDoc 就能知道会发生什么。
在 Java 8 和 Google Guava 中,结合了两种解决方案:Optional
/**
* Finds a category by its id.
*
* @param id the id
* @return the category for that id, an empty value if not found
*/
public Optional<Category> findCategoryById(int id) {
Object result = ....uniqueResult();
return Optional.ofNullable((Category) result);
}
Run Code Online (Sandbox Code Playgroud)
这里的优点是,调用者可以决定他是否期望该值存在:
// The value must exist, otherwise a NoSuchElementException is thrown:
...findCategoryById(id).get();
// The value could be null:
...findCategoryById(id).orElse(defaultValue);
Run Code Online (Sandbox Code Playgroud)
最大的问题是,许多 Java 开发人员到目前为止还不习惯它,但我想这会随着时间的推移而改进......
附加阅读材料
还有一个社区 wiki 提供了有关何时检查 null 问题的调用方的一些(或更多)要点:避免 != null 语句
| 归档时间: |
|
| 查看次数: |
14857 次 |
| 最近记录: |