Re: hibernate question ?
On Sat, 28 Aug 2010, Lew wrote:
Lew wrote:
You probably don't need to initialize 'Address#addressSet' explicitly.
I'm puzzled why people do that in entity classes. What does it provide?
Tom Anderson wrote:
The ability to say new Address().getAddressSet().add(something) without
getting a NullPointerException. Didn't we talk about this before?
That would only be guaranteed if the setter rejects or substitutes
'null' values, which the OP did not show.
I don't follow.
My understanding (caveat: i am not very familiar with JPA, and am hung
over) is that we have a situation analogous to:
public class Person {
@Id
private int id;
@OneToMany
private Set<Animal> pets;
// getters and setters
}
If you got one of these from the database, you could happily say:
person.getPets().add(someNewPet);
and everything would be okay. But if you created a new Person out of thin
air with new, it would blow up, because at that point, pets is null. Hence
the pattern of putting in an initializer which creates an empty
collection. It doesn't interfere with the case where you're getting the
object from the database, because it will immediately be overwritten with
one of Hibernate's persistent collections.
You could save the wasted objects by doing lazy initialisation of the
field, so one only gets allocated if it's needed, but i doubt the saving
would be significant in any but the most extreme situations.
In fact, they don't show a setter for that field at all, so one wonders
how any useful information gets into it.
Good point. There is a setter, but under the wrong name, where i assume
Hibernate won't find it. If the persistence annotation was on the field
instead of the getter, things would work, but it ain't.
I remain dubious about the value of preventing null in the retrieved
value. None of the other values are thus guarded. With any
non-primitive entity attribute, and that's nearly all entity attributes,
you have to check for possible 'null' values if the corresponding data
store might contain NULL.
If it's a collection, i don't think it can be null (unless you're storing
it as a serialized object rather than a database-mapped collection), since
there is no actual column holding its value - rather, there are
backreference columns in contained objects. Those could be null, but that
just means those objects aren't in any collection. If no object is
contained in the collection, won't Hibernate make it an empty collection,
rather than null?
tom
--
Every professor of philosophy needs a nine-year-old daughter. Mine has
a habit of saying, "Daddy, that is a very silly idea." She is always
right. -- AC Grayling