java - EntityManager becomes null -


i have curious error when using entitymanager. here extract of code.

@persistenceunit entitymanagerfactory factory; @resource usertransaction transaction; entitymanager em; 

inside method:

try{ datos.creardatos(docentrada); ctx.setdatosmensajes(datos); factory=persistence.createentitymanagerfactory("ealia"); transaction = (usertransaction)new initialcontext().lookup("java:comp/usertransaction"); entitymanager em = factory.createentitymanager();  //do whatever does, works fine. // here entity manager not null } catch (exception e){  } finally{     // here entity manager null          try {             svcsmensajes.grabarmensajesalida(datos, constantes.mensaje_salida_ws_usuarios_gestion, constantes.nombre_servicio_ws_usuarios_gestion, constantes.mensaje_entrada_ws_usuarios_gestion, em, ctx,transaction);         } catch (cecaexception e) {             // no devolvemos error en este caso         }          em.close();         factory.close();   } 

i don't understand why eentity manager becomes null inside finally, when @ end of try not null, when working fine, there no exceptions. trace variable , becomes null no intermediate instructions in between.

instead, if rearrange code way

    factory=persistence.createentitymanagerfactory("ealia");     transaction = (usertransaction)new  initialcontext().lookup("java:comp/usertransaction");     entitymanager em = factory.createentitymanager();      try{         datos.creardatos(docentrada);         ctx.setdatosmensajes(datos);     ....     }     .... 

everything works fine. can explain it, please?

you declared em local variable of try block here:

entitymanager em = factory.createentitymanager(); 

the variable not visible finally block. block uses 1 declared field of class.

what need change above line to:

em = factory.createentitymanager(); 

in order initialize field, not local variable.

even better, might want inject entitymanager instead of creating manually.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -