Search code examples
javajpaopenjpa

Layz loaded list gets reset upon detach from EntityManager


I have lazy 1:n relation from Bp to BpHistorisiert.

To load a Bp including the related BpHistorisiert id do

    Bp bp= entityManager.find(Bp.class, anId);
    bp.getBpHistorisiertList();

This works fine, the call to getBpHistorisiertList() loads the n side lazy as expected. However when bp gets detached, the bpHistorisiert List in bp is explicitely reset to null. I can see in the debugger that this is explicitely done by the detach funcionality of the OpenJPA EntityManager.

So my question is: How to load lazy relations and keep the values when I work with detached entities?

Bp

@Entity
@Table(name = "BP", schema = "INFOP_STAMMDATEN")
public class Bp extends BaseEntity implements EntityId, Serializable {

    /** technische ID */
    @Id
    @Column(name = ID)
    private Long id;

    @Valid
    @OneToMany(mappedBy = "bp", orphanRemoval = false, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<BpHistorisiert> bpHistorisiertList = new ArrayList<>();

}

BpHistorisiert

@Entity
@Table(name = "BP_HISTORISIERT", schema = "INFOP_STAMMDATEN")
public class BpHistorisiert implements EntityId, GueltigkeitOwner, AbkuerzungOwner, Serializable {

    @Id
    @Column(name = ID)
    private Long id;

    @NotNull
    @ManyToOne
    @JoinColumn(name = BP_ID)
    @ForeignKey
    private Bp bp;

}

Solution

  • Thanks to @crizzis answer I found the reason for this behaviour. We actually have set

    <property name="openjpa.DetachState" value="fetch-groups(DetachedStateField=true)"/>
    

    in our persistence.xml. The consequence is, that all lazy fileds of all entities are set to the java default value up on detach. For a lazy List this is null.

    So yes, this is an OpenJPA feature, not a bug.

    And after all this is even explizitely documented: https://issues.apache.org/jira/browse/OPENJPA-1913?attachmentSortBy=fileName