Java Hibernate query.list() 方法返回空列表而不是空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3599318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate query.list() method is returning empty list instead of null value
提问by Reddy
When there are no rows, both query.list()
and criteria.list()
are returning emptylist instead of a null
value.
当没有行时,query.list()
和criteria.list()
都返回空列表而不是null
值。
What is the reason behind this?
这背后的原因是什么?
采纳答案by Péter T?r?k
The reason is not to force null checks in client code, in consistency with Effective Java 2nd Edition, Item 43: Return empty arrays or collections, not nulls.
原因是不强制在客户端代码中检查空值,与Effective Java 2nd Edition 的Item 43: Return empty arrays or collections, not nulls 一致。
This makes the client code simpler and less error-prone (and most likely the method implementation as well).
这使得客户端代码更简单,更不容易出错(很可能也是方法实现)。
The null-return idiom is likely a holdover from the C programming language, in which array lengths are returned separately from actual arrays. In C, there is no advantage to allocating an array if zero is returned as the length.
null-return 习惯用法可能是 C 编程语言的保留,其中数组长度与实际数组分开返回。在 C 中,如果返回零作为长度,则分配数组没有任何优势。
回答by Sjoerd
It is consistant: a list is returned with all results, whether there are any or not.
它是一致的:返回一个包含所有结果的列表,无论是否有结果。