0
votes

I was trying to write a DAO class and use the EntityManager inside this class to perform persistance operations. My database is defined as a jta-data-source in my persistence.xml and registered accordingly as a datasource in my web application server.

So I run into a problem when using the em.persist() method of the EntityManager inside my DAO because I need a transaction. Apparently, it must be a special type of transaction called UserTransaction.

Searching for examples in the web I find that you can inject this transaction with @Resource UserTransaction utx;

But for the injection to work, my DAO class has to be initialized by the container by making it an EJB (@Stateless). Making my DAO container-managed prevents me to freely and manually initialize my DAO class.

How can I create transactions inside my DAO class without making it an EJB? Do I have to manually look in the JNDI for the UserTransaction?

1

1 Answers

0
votes

In JavaEE your DAO should indeed be managed by the container(server). Only managed components have full access to resources and contexts as specified in Java EE specifications. For example, a single transaction can be shared by many components during a single invocation, therefore the server needs to manage the lifecycle of those components and control their state.
If you annotate your DAO with @Stateless you will turn in into a Stateless Session Bean - which is and EJB bean, that is by default transaction-aware. You do not have to use EJBs - you can go with CDI +@Transactional for example, but EJBs really are the ideal building block for data access layer.
Try to spend some time reading the official JavaEE tutorial, or have a look at tons of JavaEE sample projects to get a better idea of how to develop for JavaEE.