交易未激活

时间:2013-11-24 11:56:19

标签: java hibernate jpa

我遇到了这个问题,我看不出什么错。

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

我希望通过他的身份获得客户。所以我的代码是:

... 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);
    }
}

班级Cliente我认为它已经很好地映射了。我的代码失败了,为什么?

修改

好的,我的代码在FindClientByID的方法execute()崩溃,但我真的不知道为什么。该调用似乎抛出了RuntimeException。

顺便说一句,我的Command Executor就像是

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 :(得分: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;
    }