I’m converting an Eclipselink application to use Hibernate 3.6 bundled with JBoss 6 instead, and need to modify how lazy loading is done because of this. It is not my first time using hibernate.
However, it seems that my collections become uninitialized after a merge is done. I cannot remember seeing this behaviour ever before. For example:
Entity entity = entityDAO.getEntity(id);
System.out.println(entity.getMyCollection().size()); // OK, no exception
entity = entityDAO.update(entity);
System.out.println(entity.getMyCollection().size()); // Throws LazyInitializationException
EntityDAO snippet:
public Entity getEntity(Long id){
Entity e = entityManager.find(Entity.class, id);
Hibernate.initialize(e.getMyCollection());
return e;
}
public Entity update(Entity entity){
return entityManager.merge(entity);
}
Entity snippet:
@OneToMany(mappedBy="entity", cascade=CascadeType.ALL, orphanRemoval=true)
private List<AnotherEntity> myCollection = new ArrayList<AnotherEntity>();
Is this really the expected behaviour? It seems very weird that hibernate would throw away data during merge..
That’s indeed expected behavior.
merge()consists inSo, obviously, if you don’t reinitialize the lazy collection of the returned attached entity, the collection won’t be loaded.