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

后端 未结 6 1812
迷失自我
迷失自我 2020-12-20 14:27

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

相关标签:
6条回答
  • 2020-12-20 14:45

    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.

    0 讨论(0)
  • 2020-12-20 14:45

    I had the same problem, the solution was

    @Transactional(rollbackOn = Exception.class)
    

    add to method called by Bean

    0 讨论(0)
  • 2020-12-20 15:00

    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.

    0 讨论(0)
  • 2020-12-20 15:03

    You can see below document about handle the transacion:
    Container-Managed Transactions JEE6

    use Transaction Attributes based on your application

    0 讨论(0)
  • 2020-12-20 15:03

    add @Transactional annotation on your method it will make it "transactional"

    0 讨论(0)
  • 2020-12-20 15:06

    A simple approach, add @Transactional(Transactional.TxType.REQUIRED) to method

    0 讨论(0)
提交回复
热议问题