Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Transactions in Java EE must be explicitly controlled, either using the <code>UserTransaction</code> from JNDI or using deployment descriptor/annotations on EJBs. For a CDI component, here the <code>UserController</code>, no transaction is started by default. (<strong>EDIT</strong> Transactions for EJB methods are enabled by default, if nothing is specified.)</p> <p>So to start, your assumption:</p> <blockquote> <p>the <code>UserController.updateUser()</code> will execute <code>userService.saveUser(user);</code> and <code>logService.logEvent("Saved user " + fullName)</code>; within the same transaction</p> </blockquote> <p>is wrong! I believe that a new transaction will be created and committed on each <code>em.persist()</code>/<code>em.merge()</code> call.</p> <p>In order to wrap the calls <code>saveUser()</code> and <code>logEvent()</code> in the same transaction you can manually use the <code>UserTransaction</code>:</p> <pre><code>public void updateUser(user) { InitialContext ic = new InitialContext(); UserTransaction utx = (UserTransaction) ic.lookup("java:comp/UserTransaction"); utx.begin(); ... utx.commit(); // or rollback(), wrap them in try...finally } </code></pre> <p>Or the friendlier:</p> <pre><code>@Resource UserTransaction utx; ... public void updateUser(user) { utx.begin(); ... utx.commit(); // or rollback(), wrap them in try...finally } </code></pre> <p>Or even better the <code>@Transactional</code> annotation, either with Java EE 7 or in Java EE 6 with the <a href="http://deltaspike.apache.org/jpa.html" rel="nofollow">DeltaSpike JPA extension</a> (or any other similar interceptor).</p> <pre><code>@Transactional public void updateUser(user) { ... } </code></pre> <p>You could specify that the EJB methods are transactional using the <code>javax.ejb.TransactionAttribute</code> annotation. There would still be 2 transactions in this case. Alternatively you could move the "business" logic from the web-tier to the EJB-tier in a method annotated with <code>@TransactionAttribute</code> and achieve running the DB methods in a single transaction.</p> <p>As for further reading, check out the "Support for Transactions" chapter in the EJB 3 spec.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload