smorigo 23 de abr. de 2005
Olha só a arquitetura é a seguinte:
Criei um formBean no meu struts-config.xml
& lt ; form - bean name = "loginForm" type = "org.apache.struts.action.DynaActionForm" dynamic = "true" & gt ;
& lt ; form - property name = "empresa" type = "java.lang.Long" /& gt ;
& lt ; form - property name = "usuario" type = "java.lang.String" /& gt ;
& lt ; form - property name = "senha" type = "java.lang.String" /& gt ;
& lt ; / form - bean & gt ;
Criei JavaBean
public class Empresa implements Serializable {
private Long codigo ;
private String razaoSocial ;
// meus metodos get, set, equals e hashCode
}
Criei um DAO
package br.com.fts.dao ;
import br.com.fts.util.BaseDAO ;
import br.com.fts.util.DAOException ;
import br.com.fts.util.ConnectionFactory ;
import br.com.fts.bean.Empresa ;
import java.util.Collection ;
import org.hibernate.Session ;
import org.hibernate.HibernateException ;
public class EmpresaDAO extends BaseDAO {
private static EmpresaDAO instance = null ;
public static synchronized EmpresaDAO getInstance () {
if ( instance == null ) {
instance = new EmpresaDAO ();
}
return instance ;
}
public EmpresaDAO () {
}
public Collection listaTodos () throws DAOException {
return listaTodos ( Empresa . class , null );
}
public Object procurar ( Long codigo ) {
Session session = ConnectionFactory . getInstance (). getSession ();
try {
return ( Empresa ) session . load ( Empresa . class , codigo );
} catch ( HibernateException e ) {
System . err . println ( "Hibernate Exception" + e . getMessage ());
throw new RuntimeException ( e );
} finally {
if ( session != null ) {
try {
session . close ();
} catch ( HibernateException e ) {
System . err . println ( "Hibernate Exception" + e . getMessage ());
throw new RuntimeException ( e );
}
}
}
}
}
Meu mapeamento está dessa maneira:
<?xml version="1.0"?>
< !DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
< hibernate-mapping>
< class name="br.com.fts.bean.Empresa" table="TB_EMPRESA" >
< id name="codigo" column="CD_EMPRESA" type="long">
< generator class="sequence">
< param name="sequence"> GE_CD_EMPRESA< /param>
< /generator>
< /id>
< property column="DC_RAZAO_SOCIAL" length="60" name="razaoSocial" not-null="true" type="string" lazy="false"/>
< /class>
< /hibernate-mapping>
Bem fora isso tenho uma classe de ConnectionFactory e o arquivo de configuração da conexão com meu BD que é Firebird…
valeuuuu
hmichel 23 de abr. de 2005
leomc:
Existem várias formas de contornar … Quais por exemplo?
[]'s
smorigo 23 de abr. de 2005
Bom estive lendo um pouco não consegui achar a solução mais acredito que o erro deva estar no meu ConnectionFactory
package br.com.fts.util ;
import org.hibernate.* ;
import org.hibernate.cfg.* ;
public class ConnectionFactory {
private static final SessionFactory sessionFactory ;
public static final ThreadLocal session = new ThreadLocal ();
static {
try {
Configuration cfg = new Configuration ();
cfg . configure ( "/hibernate.cfg.xml" );
sessionFactory = cfg . buildSessionFactory ();
} catch ( MappingException e ) {
System . err . println ( "Mapping Exception" + e . getMessage ());
throw new RuntimeException ( e );
} catch ( HibernateException e ) {
System . err . println ( "Hibernate Exception" + e . getMessage ());
throw new RuntimeException ( e );
}
}
public static Session currentSession () {
Session s = ( Session ) session . get ();
if ( s == null ) {
s = sessionFactory . openSession ();
session . set ( s );
}
return s ;
}
public static void closeSession () {
Session s = ( Session ) session . get ();
if ( s != null )
s . close ();
session . set ( null );
}
}
smorigo 23 de abr. de 2005
deixei a sessão aberta e ele funciono… alguém tem alguma dica de como solucionar o problema??? estou ficando doidooo rsss
Alexandre_Possebom 26 de abr. de 2006
Mude de :
return ( Empresa ) session . load ( Empresa . class , codigo );
para :
return ( Empresa ) session .get ( Empresa .class , codigo ) ;
paulohrl 15 de fev. de 2008
Gente, desculpa desenterrar esse post, mas estava tendo o mesmo problema, de Lazy Initialization Exception.
Troquei o load pelo get como sugerido pelo amigo Alexandre Possebom e funcionou, mas gostaria de entender o porque. Qual a diferença entre eles?
Obrigado desde já
paulohrl 15 de fev. de 2008
Olha o meu caso:
org . hibernate . LazyInitializationException : could not initialize proxy - no Session
at org . hibernate . proxy . AbstractLazyInitializer . initialize ( AbstractLazyInitializer . java : 57 )
at org . hibernate . proxy . AbstractLazyInitializer . getImplementation ( AbstractLazyInitializer . java : 111 )
at org . hibernate . proxy . pojo . cglib . CGLIBLazyInitializer . invoke ( CGLIBLazyInitializer . java : 150 )
at whereis . model . Usuario $$ EnhancerByCGLIB $$ b4c5fb31 . getId (& lt ; generated & gt ;)
at whereis . logic . LocalizadorLogic . main ( LocalizadorLogic . java : 34 )
at sun . reflect . NativeMethodAccessorImpl . invoke0 ( Native Method )
at sun . reflect . NativeMethodAccessorImpl . invoke ( Unknown Source )
at sun . reflect . DelegatingMethodAccessorImpl . invoke ( Unknown Source )
at java . lang . reflect . Method . invoke ( Unknown Source )
at org . vraptor . component . DefaultLogicMethod . execute ( DefaultLogicMethod . java : 117 )
at org . vraptor . interceptor . ExecuteLogicInterceptor . intercept ( ExecuteLogicInterceptor . java : 37 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at org . vraptor . interceptor . SettingAndValidationInterceptor . intercept ( SettingAndValidationInterceptor . java : 131 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at org . vraptor . interceptor . InjectionInterceptor . intercept ( InjectionInterceptor . java : 41 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at org . vraptor . interceptor . ComponentLookupInterceptor . intercept ( ComponentLookupInterceptor . java : 58 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at whereis . logic . interceptor . DAOInterceptor . intercept ( DAOInterceptor . java : 25 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at whereis . logic . interceptor . AutorizadorInterceptor . intercept ( AutorizadorInterceptor . java : 27 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at org . vraptor . interceptor . FlashScopeInterceptor . intercept ( FlashScopeInterceptor . java : 22 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at org . vraptor . interceptor . RegisterAttributesInteceptor . intercept ( RegisterAttributesInteceptor . java : 38 )
at org . vraptor . core . InterceptorsLogicFlow . execute ( InterceptorsLogicFlow . java : 72 )
at org . vraptor . core . VRaptorExecution . execute ( VRaptorExecution . java : 90 )
at org . vraptor . core . DefaultController . execute ( DefaultController . java : 42 )
at org . vraptor . VRaptorServlet . service ( VRaptorServlet . java : 70 )
at javax . servlet . http . HttpServlet . service ( HttpServlet . java : 803 )
at org . apache . catalina . core . ApplicationFilterChain . internalDoFilter ( ApplicationFilterChain . java : 290 )
at org . apache . catalina . core . ApplicationFilterChain . doFilter ( ApplicationFilterChain . java : 206 )
at org . apache . catalina . core . StandardWrapperValve . invoke ( StandardWrapperValve . java : 233 )
at org . apache . catalina . core . StandardContextValve . invoke ( StandardContextValve . java : 175 )
at org . apache . catalina . core . StandardHostValve . invoke ( StandardHostValve . java : 128 )
at org . apache . catalina . valves . ErrorReportValve . invoke ( ErrorReportValve . java : 102 )
at org . apache . catalina . core . StandardEngineValve . invoke ( StandardEngineValve . java : 109 )
at org . apache . catalina . connector . CoyoteAdapter . service ( CoyoteAdapter . java : 263 )
at org . apache . coyote . http11 . Http11Processor . process ( Http11Processor . java : 844 )
at org . apache . coyote . http11 . Http11Protocol $ Http11ConnectionHandler . process ( Http11Protocol . java : 584 )
at org . apache . tomcat . util . net . JIoEndpoint $ Worker . run ( JIoEndpoint . java : 447 )
at java . lang . Thread . run ( Unknown Source )
to usando o vRaptor e hibernate. Sempre faço uma solicitação para um logic. Tenho somente uma página, que tem um corpo onde faz várias requisições AJAX. Na primeira requisição AJAX, depois de abrir a página inicial, ocorre tudo sem problemas, ja na segunda, ocorre a excessão. Todas as páginas requisitadas utilizam o acesso ao banco. Passam por um interceptor q cria uma sessão e no final a fecha. Qual pode ser o problema? E porque com o get não ocorre?
É melhor usar o get do que o load ou o contrário? Ou tanto faz em questão de desempenho?
Valew
paulohrl 15 de fev. de 2008
Então cara,
No meu Interceptor eu crio uma instância de um DaoFactory:
public class DAOInterceptor implements Interceptor {
private final DAOFactory factory = new DAOFactory ();
public void intercept ( LogicFlow flow ) throws LogicException , ViewException {
flow . execute ();
if ( factory . hasTransaction ()) {
factory . rollback ();
}
factory . close ();
}
@Out ( key = "whereis.dao.DAOFactory" )
public DAOFactory getFactory () {
return factory ;
}
}
e no construtor do DaoFactory cria uma Session
public class DAOFactory {
private final Session session ;
private Transaction transaction ;
public DAOFactory () {
session = HibernateUtil .getSession () ;
}
public void beginTransaction () {
this .transaction = this .session .beginTransaction () ;
}
public void commit () {
this .transaction .commit () ;
this .transaction = null ;
}
public boolean hasTransaction () {
return this .transaction != null ;
}
public void rollback () {
this .transaction .rollback () ;
this .transaction = null ;
}
public void close () {
this .session .close () ;
}
}
public class HibernateUtil {
private static SessionFactory factory ;
static {
Configuration conf = new AnnotationConfiguration ();
conf . configure ();
factory = conf . buildSessionFactory ();
}
public static Session getSession () {
return factory . openSession ();
}
}
Então não entendi porque está me acusando que não tenho uma sessão.
Desculpa ficar incomodando, mas essa dúvida ta me tirando horas de sono ha dias…
Valew
paulohrl 15 de fev. de 2008
Vou por o isOpen para ver se ainda está aberta…
Valew
Depois posto o resultado.
Espero que positivo.