1 Reply Latest reply: Sep 22, 2011 2:51 AM by gimbal2 RSS

    Servlet and JTA

    egesr
      Hello,

      I've a servlet that is using JTA, but it doesn't work as I expected when I begin the transaction before finding the entity.

      The transaction is injected with the annotation:

      @Resource
      private UserTransaction utx;

      And in the servlet code I have written the next code:

      Book requestedBook = em.find(Book.class, bookId);

      utx.begin();

      int inventory = requestedBook.getInventory();

      int newInventory = inventory - 1;

      requestedBook.setInventory(newInventory);

      utx.commit();

      I don't know what is happening but the changes are not persised to the database.

      If I begin the transaction before finding the entity, it works, but I don't understand why it doesn't work when I start the transaction after finding the entity.

      Thank in advance
        • 1. Re: Servlet and JTA
          gimbal2
          egesr wrote:
          Hello,

          I've a servlet that is using JTA, but it doesn't work as I expected when I begin the transaction before finding the entity.

          The transaction is injected with the annotation:

          @Resource
          private UserTransaction utx;

          And in the servlet code I have written the next code:

          Book requestedBook = em.find(Book.class, bookId);

          utx.begin();

          int inventory = requestedBook.getInventory();

          int newInventory = inventory - 1;

          requestedBook.setInventory(newInventory);

          utx.commit();

          I don't know what is happening but the changes are not persised to the database.

          If I begin the transaction before finding the entity, it works, but I don't understand why it doesn't work when I start the transaction after finding the entity.

          Thank in advance
          Because when you start the transaction after you find the entity, the entity is not managed within that transaction. Container Managed Transactions, study it well.