Search code examples
javajpaone-to-manynull-pointer

(Open-)JPA 1.0: OneToMany-related list is null, when fetching in lazy mode


I have a problem with JPA 1.0 (OpenJPA)

Following situation

@Entity
public class A{
    private Long aId;
    private List<B> bEntities;
    //myId getter and setter
    @OneToMany(mappedBy="referencedA")
    public List<B> getBEntities(){
        return bEntities;
    }
    public void setBEntities(List<B> bEntities){
        this.bEntities = bEntities;
    }
}  

,

@Entitiy
public class B{
    private Long bId;
    private Long aId;
    private A referencedA;
    //aId/bId getter and setter
    @ManyToOne
    @JoinColumn(name="A_ID", referencedColumnName="A_ID")
    public A getReferencedA(){
        return referencedA;
    }
    public void setReferencedA(A referencedA){
        this.referencedA = referencedA;
    }
}  

If I perform the following JPQL-Query it works as expected, meaning that each attribute is filled:

select object(o) from B o  

But if I want to get all As:

select object(o) from A o  

and I try to get the B-List via aReceivedAObject.getBEntities(); it returns null.

If I change or rather extend the OneToMany annotation as follows:

@OneToMany(mappedBy="referencedA", fetch=FetchType.EAGER)  

everything works as expected.

BUT I need lazy fetching because everything else will be much too slow.

I really hope that someone can help me solving the issue as I'm stuck to the problem for three days now :(

Notes, in case its important:
I (must) use Websphere 6.1 (with Feature-Pack for EJB 3.0), which uses OpenJPA 1.0. So it's a JavaEE project.
As far as I understood the OpenJPA-Doc I need to enable the enhancement, what I have done as described here http://www.ibm.com/developerworks/websphere/techjournal/0612_barcia/0612_barcia.html#sec4f
But this doesn't seem to make any difference :(

Thanks in advance!!!
Kind Regards,
asotbb

//edit: corrected typo: changed "public List getBEntities()" to "public List getBEntities()"


Solution

  • And from another class I call ADAL's findAll method.

    Yeah that is your issue, if it is not persistence aware, you will need to make that class aware of the persistence context if you want ReceivedAObject.getBEntities() to work with lazy loading.

    Having persistence conexts all over the place though can get messy as you may be forced to manually merge entities between them. Another way you could do it is have that getBEntities() method be wrapped in the Data Access Layer (ADAL).