This discussion is archived
1 Reply Latest reply: Sep 22, 2011 12:51 AM by gimbal2 RSS

Servlet and JTA

egesr Newbie
Currently Being Moderated
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 Guru
    Currently Being Moderated
    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.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points