Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should persistent classes initialize instance variable collections

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.

like image 611
Danny Avatar asked Dec 21 '11 12:12

Danny


2 Answers

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.

like image 149
Mike Partridge Avatar answered Oct 14 '22 21:10

Mike Partridge


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 with java.util implementations
  • always code to Collection interfaces

Making it customary for Hibernate object Collections never being NULL and avoiding the pitfall noted in the above documentation of casting a Hibernate object Collection to an invalid implementation.

like image 45
Dan Cruz Avatar answered Oct 14 '22 20:10

Dan Cruz