Thursday, 18 August 2011

JPA not instantiating mapped collections.

I struggled a while now to figure out why I am getting a NullPointerException
when trying to access a mapped collection:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "cmTypedef")

private List cmParamdefs;

I instantiated a object, then em.merge() it but still I got a NPE.
I really thought that merge would populate all the fields.


Then I tried to make it Eager:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "cmTypedef",

fetch = FetchType.EAGER)
private List cmParamdefs = new ArrayList();
Still no luck :(


So merge didn't do the trick, but trying everything I saw that if I do
em.flush();

em.refresh(ret);
after the merge, then like magic the collection is populated..


Finally I remember I had this issue before and the simple solution I have so far is
to manually instantiate the collection:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "cmTypedef")

private List cmParamdefs = new ArrayList();


I'm not sure if this is the best practice, but it works and is simple..

1 comment: