Bom dia pessoal,
Estou desenvolvendo um sistema para fins didáticos e estou tendo alguns problemas com o lazy loading e a maneira correta de implementar um DAO com o HIBERNATE.
Criei um DAO generico
public class HibernateDAO<T> {
private Class<T> classe;
private Session session;
public HibernateDAO(Class<T> classe)
{
this.classe = classe;
}
public void update(T bean) throws Exception
{
Transaction tx = null;
try
{
session = HibernateUtil.openSession();
tx = session.beginTransaction();
session.update(bean);
tx.commit();
}catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
throw ex;
}finally
{
session.close();
}
}
public void delete(T bean) throws Exception
{
Transaction tx = null;
try
{
session = HibernateUtil.openSession();
tx = session.beginTransaction();
session.delete(bean);
session.flush();
tx.commit();
}catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
throw ex;
}finally
{
session.close();
}
}
public T getBean(Serializable codigo)
{
T bean = null;
try
{
session = HibernateUtil.openSession();
Transaction tx = (Transaction) session.beginTransaction();
bean = (T) session.get(classe, codigo);
tx.commit();
session.close();
}catch(Exception e)
{
e.printStackTrace();
}
return bean;
}
public void save(T bean) throws Exception
{
Transaction tx = null;
try
{
session = HibernateUtil.openSession();
tx = session.beginTransaction();
session.save(bean);
session.flush();
tx.commit();
}catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
throw ex;
}finally
{
session.close();
}
}
public void saveOrUpdate(T bean) throws Exception
{
Transaction tx = null;
try
{
session = HibernateUtil.openSession();
tx = session.beginTransaction();
session.saveOrUpdate(bean);
session.flush();
tx.commit();
}catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
throw ex;
}finally
{
session.close();
}
}
}
mas quando faço uma consulta e busco uma list obtenho um LazyLoadingException
HibernateDAO<TelaBean> ht = new HibernateDAO<TelaBean>(TelaBean.class);
TelaBean t = ht.getBean(1);
t.getPermissoes();
Eu sei que o problema esta quando fecho a sessão e tento buscar a lista
Agora minhas duvidas são:
1 - Qual a maneira correta de implementar esse DAO?.
2 - Quando é a hora correta de se fechar a session?.
Tenho essas duvidas pois estou começando a aprender Hibernate e JPA
Agradeço muito a atenção desde ja!
