java - 当它可能为空时如何从 Hibernate 返回一个唯一的结果?

标签 java hibernate

当 Hibernate 唯一结果可能为 null 时,最干净的方法是什么?

这个方案有什么问题吗:

public Category getCategoryById(int id) {
    Object result = currentSession.createCriteria(Category.class)...uniqueResult();
    return (Category) result;
}

还有更好的方法吗?

最佳答案

没有干净的方法可以做到这一点,因为它取决于您的 API。

如果您表示您的方法可以返回 null ,尤其是在 JavaDoc 中 - 可能由 @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;
}

另一方面,如果缺少的元素无效,您可以抛出异常并记录下来:

/**
 * 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;
}

(我不得不承认我只是偶尔使用注释)

我在这两种情况下使用不同的方法名称( findCategoryByIdgetCategoryById )。如果您坚持命名方案,您的 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);
}

这里的优点是,调用者可以决定他是否期望该值存在:

// The value must exist, otherwise a NoSuchElementException is thrown:
...findCategoryById(id).get();

// The value could be null:
...findCategoryById(id).orElse(defaultValue);

最大的问题是,很多 Java 开发人员到现在还不习惯,但我想这会随着时间的推移而改善...

额外的阅读 Material

关于何时检查空问题的调用方方面的一些(或更多)要点还有一个社区维基:Avoiding != null statements

关于java - 当它可能为空时如何从 Hibernate 返回一个唯一的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926068/

相关文章:

java - 更改参数数量后的 hibernate ConstraintViolationException

java - 如何有条件地加载映射到对象中的集合?

java - 关于 IntelliJ 到 Eclipse 转换的问题

java - 猜猜 secret 数字java

java - 如何提高我的软件项目的速度?

java - org.springframework.beans.NotReadablePropertyException :

hibernate - 自定义 hibernate 条件-向左联接添加条件

java - 删除与 Hibernate 的 OneToMany 关联上的记录

java - 如何将库添加到 Android 项目?

java - 哪个 ojdbc 版本支持带有 tomcat 6 的 oracle 12.1?