I have a doubt about using the constructor to initialize lists and other fields when using JPA, specifically my question is as follows:
Suppose I have an entity bean, that has lots of @OneToMany relationships, I would like to use the constructor to initialize them, so that I don’t have to use statements like this in my controllers:
myEntity=new MyEntity();
myEntity.innerList=new ArrayList<Type>();
myEntity.innerList.add(newObject);
so instead I would have:
public MyEntity(){
innerList=new ArrayList<Type>();
}
Now, the question is… will JPA call this constructor when mapping properties from the database?. I mean If I had persisted before an entire list, will the constructor run and reinitialize my entites lists?. Thanks a lot.
Yes, JPA will call the no-arg constructor of your entity. After that, your lists will be replaced by specific List implementations of your JPA engine. These lists allow lazy-loading and other functionalities needed by the JPA engine.
I wouldn’t care much about the needless
ArrayListinstantiation in this case. This is not where a typical JPA application will take the most time. I find it much more important to have clear invariants and to respect them. One of these invariants is : my entity always has a non-null list of other entities.