1
I started using Hibernate 1 month ago. I am developing a simple application from bank to college. I have an account class, which has the Withdraw Value method :
public boolean SacarValor(long numConta, double valor) {
EntityManager em = FabricaEM.getEntityManager();
Conta c = null;
try {
c = em.find(Conta.class, numConta);
em.getTransaction().begin();
if ((c.getSaldo() - valor) < 0) {//testar
return false;
} else {
c.setSaldo(c.getSaldo() - valor);
em.getTransaction().commit();
em.getTransaction().begin();//nova transacao para registrar o movimento
MovimentoDAO mdao = new MovimentoDAO();
Movimento m = new Movimento();
m.setTipoMovimento(TipoMovimento.SAQUE);
m.setDataMovimento(Calendar.getInstance());
m.setHoraMovimento(Time.valueOf(LocalTime.now()));
m.setValorMovimento(5);
m.setConta(em.find(Conta.class, numConta));
mdao.save(m, numConta);
em.getTransaction().commit();
}
return true;//removido
} catch (Exception e) {
System.err.println(e);
} finally {
em.close();
}
return false;
}
I’m hoping that when the method(Withdraw value) was executed, a movement would be registered soon after, but I’m getting the following return.
java.lang.IllegalStateException: Transaction already active Exception in thread "main" java.lang.IllegalStateException: EntityManager is closed at org.hibernate.ejb.EntityManagerImpl.close(EntityManagerImpl.java:132) at modelo.dao.ContaDAO.SacarValor(ContaDAO.java:153) at modelo.tests.ContaTeste.main(ContaTeste.java:94) Java Result: 1
How can I perform two transactions then using the same transaction?
OBS : The subtraction in the Account table is done in the BD, but no new movement is recorded.
thanks, but I tried without this line... returns the following : java.lang.Illegalstateexception: Transaction not active
– alvaro