problemas com LazyInitializationException

29/07/2009

1

Ola a todos

estava praticando hibernate , com uma aplicação, e me deparei com esse erro:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: camara.bean.Cliente.os, no session or session was closed


meu GenericDAO

public abstract class GenericDAO {
    private Session ses;
    public GenericDAO() {
    }
    protected Session getSession() {
        return HibernateUtil.getInstace().getSession();
        //return HibernateUtil.getInstace().getSessionFactory().getCurrentSession();
    }
    protected void SaveOrUpdatePojo(Serializable pojo){
        try{
            ses = getSession();
            ses.saveOrUpdate(pojo);
            ses.getTransaction().commit();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            //ses.close();
        }        
    }
    protected <T extends Serializable> T getPojo(Class<T> classToSearch, Serializable key){
        ses = getSession();
        Serializable toReturn = (Serializable) ses.get(classToSearch, key);
        ses.getTransaction().commit();
        ses.close();
        return (T) toReturn;
    }
    protected void removePojo(Serializable pojoToRemove){
        ses = getSession();
        ses.delete(pojoToRemove);
        ses.getTransaction().commit();
        ses.close();

    protected Serializable getPurePOJO(String query, Object... params){
        Object toreturn=null;
        //Session ses=null;
        try{
        ses = getSession();
        Query qr = ses.createQuery(query);
        for (int i = 1; i <= params.length; i++) {
            qr.setParameter(i-1, params[i-1]);
        }
        toreturn = qr.uniqueResult();
        ses.getTransaction().commit();
        } catch (HibernateException e){
            e.printStackTrace();
        } finally {
            ses.close();
        }        
        return (Serializable) toreturn;
    }

    protected <T extends Serializable> List<T> getPureList(Class<T> classToSearch,String query, Object... params){
        List<T> toreturn=null;
        try{
           ses = getSession();
            Query qr = ses.createQuery(query);
            for (int i = 1; i <= params.length; i++) {
                qr.setParameter(i-1, params[i-1]);
            }
            toreturn = qr.list();
            ses.getTransaction().commit();
        } catch (Exception e){
            e.printStackTrace();
            ses.getTransaction().rollback();
        } finally {
            ses.close();
        }        
        return toreturn;
    }
    public void Close(){
       getSession().close();
       ses = null;
    }


Meu Hibernate Util:

public class HibernateUtil {
    private static HibernateUtil me;   
    private SessionFactory sessionFactory;
    public HibernateUtil() {
          sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
    }
    public Session getSession(){        
        Session toReturn = sessionFactory.openSession();
        toReturn.beginTransaction();
        return toReturn;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public static HibernateUtil getInstace(){
        if (me==null){
            me = new HibernateUtil();
        }
        return me;
    }
}


o meu bean Clinte
@Entity
@Table(name="cliente")
public class Cliente implements java.io.Serializable {
    ...

    @OneToMany(mappedBy="cliente",fetch=FetchType.EAGER)
    @Cascade(value={CascadeType.ALL,CascadeType.DELETE_ORPHAN})
    private List<Contato> contato;

    @Temporal(TemporalType.DATE)
    @Column(name="cadastro")
    private Date datacadastro;

    @OneToMany(mappedBy="clientedebito",fetch=FetchType.LAZY)
    private List<ContasReceber> contasreceber;

   
    @OneToMany(mappedBy="cliente")

    private List<OrdemServico> os;

...

//gets e sets


Classe OrdemServico
@Entity
@Table(name="ordemservico")
public class OrdemServico implements java.io.Serializable {
 ...   
    @ManyToOne
    @JoinColumn(name="cliente")
    @Cascade(CascadeType.SAVE_UPDATE)
    private Cliente cliente;
   
...

    @OneToMany(mappedBy = "ordemservico",fetch=FetchType.LAZY)
    @Cascade(value={CascadeType.ALL,CascadeType.DELETE_ORPHAN})
    
    private List<DetalheOSProd> detalheosprod;
    
    @OneToMany(mappedBy = "ordemservico",fetch=FetchType.LAZY)
    @Cascade(value={CascadeType.ALL,CascadeType.DELETE_ORPHAN})
    private List<DetalheOSServ> detalheosserv;
    
...

//gets e sets



Alguem saberia como posso resolver esse problema?

ps. Li sobre o Padrão Open Session in View [url]https://www.hibernate.org/43.html[/url] ,mas não entendi de como aplicar ele ao meu codigo
Responder

Posts

30/07/2009

Rlazoti

Realmente seu problema é resolvido com Open Session In View.

Este problema occore quando voce tenta acessar na sua view associacoes que não foram carregadas no seu DAO.

Voce tentou implementar, qual a duvida ou erro?
Responder