Hibernate中的空集合与空集合 [英] Null vs empty collections in Hibernate
问题描述
public class ClassA {
@OneToMany(fetch = EAGER)
私人列表< ClassB> bList;
当我读取 ClassA
从一个Hibernate会话中, bList
字段用 PersistentList
对象进行初始化, p>
我发现自己需要在列表为空的情况下,我需要Hibernate将 bList
字段初始化为 null
,而不是空的 PersistentList
。从理论上讲,Hibernate有它需要的信息来做这件事,因为列表上的提取是渴望的。问题在于,根据 Hibernate文档的第6.1节:
$ b
由于底层关系
模型,集合值属性
不支持null价值语义。
Hibernate不区分
a空集合引用和
空集合。
这使得完美的感觉,但我希望有人能想出一个狡猾的诡计来克服这个限制。我在想,也许一些监听/回调机制可能允许我用空引用替换空列表。
你试过检查getbList()方法?你可以这样做: if(bList.isEmpty())
return null;
返回bList;
Hibernate将始终为您的引用创建一个对象,但您可以控制吸气剂和吸附剂。如果列表中有0个元素,则可以始终返回null。
Say I have the following Hibernate-mapped class:
public class ClassA {
@OneToMany(fetch=EAGER)
private List<ClassB> bList;
}
When I read an object of ClassA
from a Hibernate session, the bList
field is initialized with a PersistentList
object, as expected.
I find myself with a requirement where in situations where the list is empty, I need Hibernate to initialize the bList
field to null
, rather than with an empty PersistentList
. In theory, Hibernate has the information it needs to do this, since the fetch on the list is eager. The problem is that according to section 6.1 of the Hibernate docs:
Due to the underlying relational model, collection-valued properties do not support null value semantics. Hibernate does not distinguish between a null collection reference and an empty collection.
This makes perfect sense, but I'm hoping someone can come up with a cunning ruse to overcome this limitation. I'm thinking perhaps some listener/callback mechanism might allow me to replace empty lists with null references.
Have you tried to check in the getbList() method? You could do:
if(bList.isEmpty())
return null;
return bList;
Hibernate will always create an object for your references, but you are allowed to control the data inside of the getter and setters. If the list has 0 elements you can always return null.
这篇关于Hibernate中的空集合与空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!