JustDanyul
JustDanyul

Reputation: 14044

Hibernate constructors

Is there any problem in initializing Sets in the constructor of a class persisted with hibernate?

I'm having issues with .equal implementations because if a object is loaded with hibernate, its sets are initialized even if they are empty, i.e. they are just empty sets. Where in a newly constructed object, they are null. I know this could be handled in the equal method but its a bit messy since, null isn't really equal to a empty set.

The reason I left out the constructor, if that I figured that from a performance point of view that would be no point in initializing the class's Set properties (creating new HashSets or something like that), and then have hibernate reinitialize them (I'm guessing it would?).

Should I just not worry about this and initialize the Set data structures in the constructor? or maybe create a special constructor for the case of manual initialization of a new instance.

Upvotes: 1

Views: 435

Answers (1)

JB Nizet
JB Nizet

Reputation: 691775

Your objects should have invariants, and one of these invariants is that collections are never null. They can be empty, but not null. So yes, you should instantiate empty sets from the constructor.

The cost of doing this is negligible compared to the work Hibernate does, the network calls to the database, etc. You won't notice any difference in performance.

Upvotes: 5

Related Questions