2015-11-25 33 views
2

什么是最简洁的方式返回一个Hibernate的独特结果,当它可能是null如何从Hibernate返回可能为空的唯一结果?

这有什么错与此解决方案:

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

,并有更好的方法来做到这一点?

+0

我的问题更多的是最彻底的方法当它可能为空时返回一个hibernate唯一结果。 –

+0

我从你的问题中删除了_downcast_方面,因为这与它无关。 –

回答

1

有没有干净的方式做到这一点,因为它取决于您的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; 
} 

(我不得不承认,我只用偶尔的注解)

我正在使用不同的方法名称(findCategoryById v.s. getCategoryById)。如果你坚持一个命名方案,你的API的用户将会知道在不阅读JavaDoc的情况下会发生什么。

在Java 8和谷歌番石榴有两种解决方案的组合: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开发者不使用它到现在为止,但我想这将及时改进......

补充阅读材料

有一个社区的wiki以及有关的发送方的一些(或更多)点时,检查空问题Avoiding != null statements

相关问题