Transaction is required to perform this operation (either use a transaction or extended persistence context)

Basically one is in the presence of a container managed JTA aware persistence context with bean managed transactions (BMT).

Therefore, besides your EntityManager you should also inject, into your DataFetchBean, your UserTransaction, in order to begin, commit or rollback a transaction.

@Named
@RequestScoped
public class DataFetchBean {
    @PersistenceContext
    EntityManager em;

    @Resource
    private UserTransaction userTransaction;

    ...
}

Then, in your addEmployee method, you've to begin and then commit your transaction, so your changes to your employee entity can be propagated to the database.

public void addEmployee() throws Exception {
    Employee employee = new Employee(500000, new Date(335077446), "Josh", "Carribean", 'm', new Date(335077446));

    userTransaction.begin();
    em.persist(employee);
    userTransaction.commit();
}

In spite of this, you should think about migrating the database actions into an EJB, injecting it into your JSF bean, therefore delegating on the container the onus of managing the transactions, i.e. make use of CMT, instead of manually handling them.


An alternate way to handle this is to use the annotation @Transactional on your DataFetchBean's method addEmployee. Then you don't need the UserTransaction and can use AOP to manage the transaction.

This was a new feature added in JTA 1.2.