I\'m using Wildfly 10.0.0 Final, Java EE7, Maven and JPA 2.1. When I am querying my database for records it works fine and lists out the employees, but when I am trying to p
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.
I had the same problem, the solution was
@Transactional(rollbackOn = Exception.class)
add to method called by Bean
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.
You can see below document about handle the transacion:
Container-Managed Transactions JEE6
use Transaction Attributes
based on your application
add @Transactional annotation on your method it will make it "transactional"
A simple approach, add @Transactional(Transactional.TxType.REQUIRED)
to method