Hi, I'm having trouble defining the initialisation rules for the data in my persisted classes. Sometimes, we create the object (and need to populate it) and sometimes, Hibernate creates the object (when retrieving from database).
I'd like to come up with some safe, consistent and workable rules but I am a bit stuck. In particular, I would like to know when it is ok to assign some initial, default value to attributes of the class (knowing that Hibernate will overwrite these if it has to call the set method, and maybe will overwrite with a proxy if the data is lazyloaded set or association).
So far, I have:
Code:
public class MyClass {
private int xyz; // no sensible default probably
private boolean xyz = false; // possibly a sensible default
private Boolean xyz; // depending on application context, one could have a sensible default?
private Date xyz; // no sensible default
private String xyz; // no sensible default except "" perhaps
private Set xyz = new HashSet(); // Hibernate can cope with this and sets an Empty Set, not null, so this is consistent
private Component xyz; // THIS I'M STUCK ON, IT'S A COMPONENT IN SAME TABLE, should it be null or new Component();
private SingleValueAssociation xyz; // Associated attribute from another table, same question as for the Component
// Empty or no constructor
public MyClass
{
}
// Simple gets/sets; no lazy initialisation
public Boolean getXyz()
{
return xyz;
}
public void setXyz(Boolean new)
{
this.xyz = new;
}
}
The gets/sets are simple and don't try to create objects if they don't exist.
Where we have to create the object, and need to create initial Dates, Booleans, Components, we are doing these in separate methods as follows:
Code:
public void initialiseMyClass()
{
xyz = new Component();
}
1) Is this approach good/bad?
2) Can I go ahead and define sensible defaults e.g. new Component() upfront? Or is this going to cause confusion for developers who may go on to create objects upfront just to avoid NPEs?
3) Should I set up the defaults in the constructor? Is this the same potential problem as 2)?
4) Ideally I think I want to initialise data to the same sort of thing Hibernate would set if it didn't have a database value. Yes?
thanks!