-1

I'm developing a web application under JSF 2.0 + Hibernate as ORM. I was tired of having problems everytime I had to load a lazy collection so I found an approach which consists on load the collection in its getter method into my POJO classes class by means of a DAO class if this is an instance of the PersistentBag class.

Basically is something like:

public List<Entity> getLazyCollection()
{
    if (this.lazyCollection instanceof PersistentBag)
    {
        this.lazyCollection = EntityDAO.findById(this.id);
    }

    return this.lazyCollection;
}

How right/wrong is this approach in your opinion? Thank you.

Edit: I didn't make myself clear. The load is done in my POJO classes, not into the JSF Beans.

Iván
  • 552
  • 8
  • 16
  • This is going to reload the collection every time the getter is hit? – Evan Knowles May 20 '14 at 07:22
  • What exactly is the problem you are trying to solve? – Aleksander Blomskøld May 20 '14 at 07:24
  • @EvanKnowles I don't think so, because when the collection is loaded for a concrete instance the class of the lazyCollection member is the actual List class, not the hibernate "proxy" class PersistentBag, so the if checks fails and returns the lazyCollection member. The problem I had is that everytime Hibernate tried to initialize a Lazy collection it failed because the Hibernate session was "closed". – Iván May 20 '14 at 07:36

1 Answers1

1

This will load the Collection from the Hibernate Session every time it is requested, which could be many times per HTTP request. Using JSF 2.x, your best is to load the Collection itself on bean's constructor/initializer and use this buffer instead of accessing the Hibernate Entity property each time:

@ManagedBean
@ViewScoped
public class ManagedBean{

    List<Entity> lazyCollection;

    public void init(){
        if (!FacesContext.getCurrentInstance().isPostback()) {
            lazyCollection = new ArrayList(EntityDAO.findById(this.id));
        }
    }

    //Getter

}
<f:metadata>
    <f:event type="preRenderView"
        listener="#{managedBean.init()}" />
</f:metadata>

That's by the way an issue about how you manage your Hibernate Sessions in your application. You get LazyInitializationException because the Session has already expired because you probably are implementing a Session per Request strategy. You've got no warranty for Hibernate to be able to recover unloaded values in the next interaction with the view.

Solution goes either having your values already stored in your Managed Bean or enabling Hibernate to load them.

See also:

Community
  • 1
  • 1
Aritz
  • 30,971
  • 16
  • 136
  • 217