2015-05-14 60 views
0

使用EntityManager時出現奇怪的錯誤。這是代碼的摘錄。EntityManager變爲空

@PersistenceUnit 
EntityManagerFactory factory; 
@Resource 
UserTransaction transaction; 
EntityManager em; 

裏面的方法:

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 it does, everything works fine. 
// HERE THE ENTITY MANAGER IS NOT NULL 
} 
catch (Exception e){ 

} 
finally{ 
    // HERE THE ENTITY MANAGER IS 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(); 
    } 

我不明白爲什麼eentity經理變成裏面的最後,當只是在嘗試的,到底是不是空的時候一切正常空,沒有例外。我跟蹤這個變量,它變成了null,沒有中間的指令。

相反,如果我這種方式重新排列碼

factory=Persistence.createEntityManagerFactory("ealia"); 
    transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction"); 
    EntityManager em = factory.createEntityManager(); 

    try{ 
     datos.crearDatos(docEntrada); 
     ctx.setDatosMensajes(datos); 
    .... 
    } 
    .... 

一切工作正常。任何人都可以解釋一下嗎?

回答

0

你宣佈em作爲這裏的try塊的局部變量:

EntityManager em = factory.createEntityManager(); 

該變量不是到finally塊可見。該塊使用您聲明爲班級字段的那個塊。

你需要的是改變上述行:

em = factory.createEntityManager(); 

爲了初始化你的領域,而不是一個局部變量。

更好的是,您可能希望注入EntityManager而不是手動創建它。

+0

Ups,這是一個愚蠢的錯誤...不能相信我沒有看到它。謝謝你的方式:) – JavierTP

+0

沒問題。爲了避免這種錯誤,你應該使用一個很好的語法着色,使字段,局部變量和方法參數看起來不同。不要忘記打勾和upvote,如果它幫助你;-) – Joffrey