pumukel
pumukel

Reputation: 81

Java-ee transaction in pojo

Is it possible to do transactions in java-ee inside a pojo without using ejb? How would the code look like? I'm using only pojos for my business processes and not creating any ejb. Is it wise?

Thanks in advance

Upvotes: 0

Views: 752

Answers (2)

Klaus Groenbaek
Klaus Groenbaek

Reputation: 5035

If you are using Java EE 7, any managed bean (or bean method) can use the @Transactional annotation to have the container manage the transaction. So this will work for WebServlet, any injected bean/pojo, as well as EJBs. Here is an example for a JAX-RS controller bean:

@Path("/debug")
public class DebugController {

    @PersistenceContext
    EntityManager entityManager;

    @GET
    @Transactional
    public String insertPerson() {

        Person person = new Person();
        person.setName("peter");
        entityManager.persist(person);
        return "OK";

    }
}

In this case the container will create and manage the transaction needed for JPA's EntityManager persist operation to store a Person in the database.

You can also @Inject the UserTransaction (or look it up in JNDI) and manage the scope of the transaction yourself, however this requires that your transactional resource explicitly joins the transaction, in that case the example would look like this:

@Path("/debug")
public class DebugController {

    @PersistenceContext
    EntityManager entityManager;

    @Inject
    UserTransaction utx;

    @GET
    public String insertPerson() throws Exception {

        utx.begin();
        try {
            entityManager.joinTransaction();
            Person person = new Person();
            person.setName("peter");
            entityManager.persist(person);
            utx.commit();
        } catch (RuntimeException e) {
            utx.rollback();
            throw e;
        }
        return "OK";

    }
}

Notice the difference in the exception handling. This is because the container will automatically roll back transactions created with @Transactional when a RuntimeException is thrown (as per JTA specification section 3.7), if you use UserTransaction directly that is your responsibility.

Upvotes: 2

Andy Guibert
Andy Guibert

Reputation: 42926

It is possible to use Java EE transactions in any class that is "container managed", which allows you to look up or inject objects.

I think the most straightforward example of using a Java EE transaction is with a JNDI lookup in a servlet:

public class MyServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    UserTransaction tran = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    tran.begin();
    // do some stuff
    tran.commit();
  }
}

This is basically what's going on under the covers with EJBs and their transaction annotations.

Upvotes: 1

Related Questions