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.
Doing static initialization as in your first code block cuts down on the need for null checking, and if you know that you'll be using the collection in the majority of use cases, it makes sense.
If, on the other hand, the collection is rarely used, it makes more sense to defer initialization until you actually need to use it.
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:
Collections
with java.util
implementationsCollection
interfacesMaking 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With