1 Reply Latest reply on Feb 24, 2005 5:06 PM by Luca Stancapiano

    HibernateContext and Transaction

    Anson Wa Newbie

      I have created a Har and depoly with a ear succesfully according to the Jboss doc. http://docs.jboss.org/jbossas/jboss4guide/r2/html/ch13.html

      Now, I would like to call Hibernate in servlet and do some saveorupdate ,but I failed.

      I tried this code

      InitialContext ctx = new InitialContext();
      SessionFactory factory = (SessionFactory)
      Session hsession = factory.openSession();
      hsession.saveOrupdate(whatever. . . .. . )


      But nothing is saved to database and no exception is throw..

      Then , I turned into this...

      The getSession method returns a Hibernate session that is linked to the current JTA transaction. Naturally this requires that a JTA transaction exist prior to the call. The following code illustrates the use of getSession.

      Session hsession = HibernateContext.getSession("java:/hibernate/CaveatEmptorSessionFactory");

      But then I failed and a exception say Icannot start a transaction outside the bind of JTA transaction .

      So How do I use the method
      Session hsession = HibernateContext.getSession

      Is it true that I should create a session bean and call the above line in a session bean metod?

      If yes, should I set the transaction-type to in the deployment descrptor or something else?
      Also, do I need those session.close() or transaction.begin() transaction.commit() code?

        • 1. Re: HibernateContext and Transaction
          Luca Stancapiano Expert

          hi ansonau.....the line

          Session hsession = HibernateContext.getSession

          is used only in a transaction. It take the current transaction and it continue with it. After if i execute a session.close(), anyhow i have to wait the end of the transaction, if no no commit will be executed.

          Then the line

          SessionFactory factory = (SessionFactory)

          create a new transaction and it will be closed by the close() method. No deployment descriptor or other thing can to be used to configure a transaction with hibernate.