2013-11-24 89 views
0

我得到這個問題,我看不出什麼是錯的。交易不活躍

Exception in thread "main" java.lang.IllegalStateException: Transaction not active 

我想通過他的ID獲得一個客戶端。所以,我的代碼是:

... somewhere at UI Layer ... { 
    ... 
    Cliente c = ServicesFactory.getClientService().clientWith(id); 
    ... 
} 

哪裏clientWith是一樣的東西:

@Override 
    public Cliente clientWith(Long id) throws BusinessException { 
     return (Cliente) executor.execute(new FindClientByID(id)); 
    } 

而且FindClientById與此代碼的命令

public class FindClientByID implements Command { 

    private Long id; 

    public FindClientByID(Long id) { 
     this.id = id; 
    } 

    @Override 
    public Object execute() throws BusinessException { 
     return ClienteFinder.findById(id); 
    } 
} 

而且ClienteFinder是:

public class ClienteFinder { 

    public static Cliente findById(Long id) { 
     return Jpa.getManager().find(Cliente.class, id); 
    } 
} 

類客戶端我認爲這是很好的映射。我的代碼失敗了,爲什麼?

編輯

好吧,我的代碼崩潰在FindClientByID的方法execute(),但我真的不知道爲什麼。該調用似乎會引發RuntimeException。

順便說一句,我的命令執行是一樣的東西

public Object execute(Command command) throws BusinessException { 

     EntityManager em = Jpa.createEntityManager(); 
     EntityTransaction trx = em.getTransaction(); 
     trx.begin(); 

     Object ret = null; 
     try { 
      ret = command.execute(); // <-- This line throws RuntimeException 
      trx.commit(); 
     } catch (BusinessException bex) { 
      if(trx.isActive()) 
       trx.rollback(); 
      throw bex; 
     } catch (RuntimeException tex) { 
      if(trx.isActive()) 
       trx.rollback(); 
      trx.rollback(); 
      throw tex; 
     } finally { 
      if(em.isOpen()) 
       em.close(); 
     } 



     return ret; 
    } 

感謝球員:d

+1

您使用哪種交易? –

+0

我不知道,我只是在這個新手。我如何檢查它? – tehAnswer

回答

0

的問題是在一個陷阱。多謝你們。

public Object execute(Command command) throws BusinessException { 

     EntityManager em = Jpa.createEntityManager(); 
     EntityTransaction trx = em.getTransaction(); 
     trx.begin(); 

     Object ret = null; 
     try { 
      ret = command.execute(); // <-- This line throws RuntimeException 
      trx.commit(); 
     } catch (BusinessException bex) { 
      if(trx.isActive()) 
       trx.rollback(); 
      throw bex; 
     } catch (RuntimeException tex) { 
      if(trx.isActive()) 
       trx.rollback(); 
      trx.rollback(); <--- **The problem was here.** 
      throw tex; 
     } finally { 
      if(em.isOpen()) 
       em.close(); 
     } 



     return ret; 
    }