持久化类应该初始化实例变量集合 [英] Should persistent classes initialize instance variable collections
问题描述
在我的Hibernate类中,应该初始化实例集合
public class Basket {
private List items = new ArrayList ();
...获得者和设置者...
}
或保持原始状态
公共类篮子{
私人列表项目;
...获得者和设置者...
}
它对Hibernate有什么不同?我遇到了这个 Hibernate文档,它初始化它们的HashSet,但我经常看到它们保持未初始化。
持久集合 code>
文档:
由于底层关系模型,集合值属性不支持空值语义。 Hibernate没有区分一个空集合引用和一个空集合。
和...
当您通过调用persist()使实例持久化时,Hibernate实际上会用Hibernate自己实现Set的实例来替换HashSet。
这些非空集合和持久与非持久语义有时会被开发人员所迷失。为了让Hibernate对象简单化,我更喜欢:
- 总是初始化所有
集合
使用java.util
实现 - 总是编码为
Collection
interfaces >
习惯使用Hibernate对象 Collection
永远不会是NULL,并且避免陷入上述将Hibernate对象 Collection
转换为无效实现的文档。
In my Hibernate classes should instance collections be initialized
public class Basket {
private List items = new ArrayList();
...getters and setters...
}
or left uninitalized
public class Basket {
private List items;
...getters and setters...
}
does it make any kind of difference for Hibernate? I came across this Hibernate documentation where it initializes their HashSet, but I have often seen them left uninitialized.
From Hibernate's persistent collection
documentation:
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.
And ...
When you make the instance persistent, by calling persist(), Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set.
These "non-null collection" and "persistent" versus "non-persistent" semantics sometimes gets lost with developers. To keep things simple with Hibernate objects, I prefer:
- always initialize all
Collections
withjava.util
implementations - always code to
Collection
interfaces
Making it customary for Hibernate object Collection
s never being NULL and avoiding the pitfall noted in the above documentation of casting a Hibernate object Collection
to an invalid implementation.
这篇关于持久化类应该初始化实例变量集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!