Re:no session or session was closed

Vejo duas saídas possíveis:

1 - Percorra a coleção do objeto a164Infracao antes de chamar closeMySession();

2 - Carregue os elementos relativos ao objeto a164Infracao numa consulta em separado, e em seguida faça:

a164Infracao.setA165ParametrizacaoInfracaos(new LinkedHashSet<A165ParametrizacaoInfracao>(
  elementosCarregadosNaConsultaEmSeparado));

Depois disso você poderá percorrer a coleção sem problemas. (Suponho que você está usando um Set para a coleção).

Estou com o seguinte erro, alguem pode me ajudar?

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.cbcconfig.bean.A164Infracao.a165ParametrizacaoInfracaos, no session or session was closed

Segue meu mapeamento do hibernate util.


/**
 * Pacote contendo as classes de auxilio ao Hibernate
 */
package br.com.cbcconfig.hibernate;

import java.io.Serializable;
import java.net.URL;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.cbcconfig.bean.A151Usina;
import br.com.cbcconfig.bean.A152Usuario;

/**
 * Classe util do Hibernate
 *
 * @author Márcio André Ishida (EWAVE)
 * @size 22/10/2010
 * @version 1.0
 */
public final class HibernateUtil {
	private static SessionFactory sessionFactory;
	
	private static SessionFactory SESSION_FACTORY;

	@SuppressWarnings("unchecked")
	private static final ThreadLocal THREAD_SESSION = new ThreadLocal();
	
	@SuppressWarnings("unchecked")
	private static final ThreadLocal THREAD_TRANSACTION = new ThreadLocal();
	
	protected static SessionFactory getSESSION_FACTORY() {
		return SESSION_FACTORY;
	}

	private static synchronized void loadSessionFactory() {
		if (sessionFactory == null) {
			try {
				//Obtendo URL para o arquivo de configuração do hibernate
				URL hibernateConfigUrl = Thread.currentThread().getContextClassLoader().getResource("hibernate.cfg.xml");			
				sessionFactory = new Configuration().configure(hibernateConfigUrl).buildSessionFactory();				
			} catch (Exception e) {				
				throw new ExceptionInInitializerError(e);
			}
		}
	}

	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			loadSessionFactory();
		}
		return sessionFactory;
	}
	
	public static void closeMySession() throws HibernateException{
		Session s = getSession();
		
		if(s != null && s.isOpen())
			s.close();
	}
	
	@SuppressWarnings("unchecked")
	public static Session getSession() throws HibernateException {
		Session s = (Session)  THREAD_SESSION.get();
		try {
			if (s == null || !s.isOpen()) {
				s =  HibernateUtil.getSessionFactory().getCurrentSession();
				THREAD_SESSION.set(s);
			}
		} catch (HibernateException ex) {
			throw new HibernateException(ex);
		}
		
		return s;
	}
	@SuppressWarnings("unchecked")
	protected static void closeSession() throws HibernateException {
		try {
			 Session s = (Session) THREAD_SESSION.get();			
			THREAD_SESSION.set(null);
			if (s != null && s.isOpen())
				s.close();
		} catch (HibernateException ex) {
			throw new HibernateException(ex);
		}
	}

	
	@SuppressWarnings("unchecked")
	protected static void beginTransaction() throws HibernateException {
		Transaction tx = (Transaction)  THREAD_TRANSACTION.get();
		try {
			if (tx == null) {
				tx =  getSession().beginTransaction();
				 THREAD_TRANSACTION.set(tx);
			}
		} catch (HibernateException ex) {
			 closeSession();
			throw new HibernateException(ex);
		}
	}

	
	@SuppressWarnings("unchecked")
	protected static void commitTransaction() throws HibernateException {
		Transaction tx = (Transaction) THREAD_TRANSACTION.get();
		try {
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
				tx.commit();
			THREAD_TRANSACTION.set(null);
		} catch (HibernateException ex) {
			 rollbackTransaction();
			throw new HibernateException(ex);
		}
	}

	
	@SuppressWarnings("unchecked")
	protected static void rollbackTransaction() throws HibernateException {
		Transaction tx = (Transaction) THREAD_TRANSACTION.get();
		try {
			 THREAD_TRANSACTION.set(null);
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
				tx.rollback();
		} catch (HibernateException ex) {
			throw new HibernateException(ex);
		}
	}
		
	@SuppressWarnings("unchecked")
	public static void save(AbstractBean bean) throws HibernateException {
		try {			
			 beginTransaction();
			 getSession().save(bean);
			 getSession().flush();
			 commitTransaction();
		} catch (HibernateException e) {
			 rollbackTransaction();
			throw new HibernateException("Falha ao salvar o objeto : " + bean.toString()+"("+e.getMessage()+")", e.getCause());
		}finally{
			closeMySession();
		}
	}
	
	
	public static void update(AbstractBean bean) throws HibernateException {
		try {
			 beginTransaction();
			 getSession().update(bean);
			 getSession().flush();
			 commitTransaction();
		} catch (HibernateException e) {
			 rollbackTransaction();
			throw new HibernateException("Falha ao atualizar o objeto : " + bean.toString()+"("+e.getMessage()+")", e.getCause());
		}finally{
			closeMySession();
		}
	}
	
	
	public static void excluir(AbstractBean bean) throws HibernateException {
		try {
			 beginTransaction();
			 getSession().delete(bean);
			 getSession().flush();
			 commitTransaction();
		} catch (HibernateException e) {
			 rollbackTransaction();
			throw new HibernateException("Falha ao exclu o objeto : " + bean.toString()+"("+e.getMessage()+")", e.getCause());
		}finally{
			closeMySession();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static Object load(Class refClass, Serializable key) throws HibernateException {
		Object obj = null;
		try {
			beginTransaction();
			obj = getSession().get(refClass, key);
			commitTransaction();
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
			   throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return obj;
	}
	
	@SuppressWarnings("unchecked")
	public static List createCriteriaList(Class persistentClass) throws HibernateException {
		List lista = null;
		try {
			beginTransaction();
			lista = getSession().createCriteria(persistentClass).list();
			commitTransaction();			
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
			   throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return lista;
	}

	@SuppressWarnings("unchecked")
	public static List createQueryList(String query) throws HibernateException {
		List resultado = null;
		try {
			beginTransaction();
			resultado = getSession().createQuery(query).list();
			commitTransaction();
			
			//   createQueryList(query, getSession());
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
			   throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return resultado;
	}
	
	@SuppressWarnings("unchecked")
	public static List iLike(Class clazz, String atributo, String parametro) throws HibernateException {
		List resultado = null;
		try {
			//MatchMode.START -> Comeca com o parametro
			//MatchMode.ANYWHERE -> Contem o parametro
			beginTransaction();
			Criteria cri = getSession().createCriteria(clazz);
			cri.add(Restrictions.ilike(atributo, parametro, MatchMode.START));
			resultado = cri.list();
			commitTransaction();			
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
				throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return resultado;
	}
	
	@SuppressWarnings("unchecked")
	public static List validarUsuarioSenha(Class clazz, String parametro, String parametro1, A151Usina a151Usina) throws HibernateException {
		List result = null;
		try {
			beginTransaction();
			Criteria cri = getSession().createCriteria(clazz);
			cri.add(Restrictions.eq("a152Login", parametro));
			cri.add(Restrictions.eq("a152Senha", parametro1));
			cri.add(Restrictions.eq("a151Usina", a151Usina));
			result = cri.list();
			commitTransaction();
			
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
				throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return result;
	}
	
	
	/**
	 * Método que executa native query
	 * @param query
	 * @throws AGHibernateException
	 */
	public static void createNativeQuery(String query) throws HibernateException {
		try {
			beginTransaction();
			getSession().createSQLQuery(query).executeUpdate();
			getSession().flush();
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
			   throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
	}
		
	
	@SuppressWarnings("unchecked")
	public static List createCriteriaInteger(Class persistentClass, String atributo, int parametro) throws HibernateException {
		List result = null;
		try {
			beginTransaction();
			Criteria cri = getSession().createCriteria(persistentClass);
			cri.add(Restrictions.eq(atributo, parametro));
			result = cri.list();
			commitTransaction();
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
			   throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public static List createCriteriaAssociativa(Class clazz, A152Usuario a152Usuario) throws HibernateException {
		List result = null;
		try {
			beginTransaction();
			Criteria cri = getSession().createCriteria(clazz);
			cri.add(Restrictions.eq("a152Usuario", a152Usuario));
			result = cri.list();
			commitTransaction();
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
				throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}finally{
			closeMySession();
		}
		return result;
	}
	
	/*@SuppressWarnings("unchecked")
	public static List createQueryList(String query, Session session) throws HibernateException {
		List list = null;
		try {
			beginTransaction();
			list = session.createQuery(query).list();
			commitTransaction();
			return list;
		} catch (Exception e) {
			if ((e.getCause() != null) && (e.getCause().getMessage() != null))
			   throw new HibernateException(e.getCause().getMessage());
			throw new HibernateException(e);
		}
	}*/
	
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 22/10/2010 15:58:02 by Hibernate Tools 3.3.0.GA -->
<hibernate-mapping>
    <class name="br.com.cbcconfig.bean.A164Infracao" table="a164_infracao" schema="public">
        <id name="a164CodigoInfracao" type="short">
            <column name="a164_codigo_infracao" />
            <generator class="sequence">
                <param name="sequence">seq_a164_infracao</param>
	        </generator>      
        </id>
        <property name="a164Nome" type="string">
            <column name="a164_nome" length="64" not-null="true" />
        </property>
        <property name="a164Descricao" type="string">
            <column name="a164_descricao" length="256" />
        </property>
        <set name="a165ParametrizacaoInfracaos" table="a165_parametrizacao_infracao" inverse="true" lazy="true" fetch="select" cascade="all-delete-orphan" outer-join="true">
            <key>
                <column name="a164_codigo_infracao" />
            </key>
            <one-to-many class="br.com.cbcconfig.bean.A165ParametrizacaoInfracao" />
        </set>
        <set name="v164Infracaos" table="v164_infracao" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="a164_codigo_infracao" not-null="true" />
            </key>
            <one-to-many class="br.com.cbcconfig.bean.V164Infracao" />
        </set>
    </class>
</hibernate-mapping>

quando tento fazer

dá erro aqui a164Infracao.getA165ParametrizacaoInfracaos()

agradeço desde já