In JBoss/WildFly should I enable JTA on data source to use with JPA?

后端 未结 3 897
悲哀的现实
悲哀的现实 2021-01-06 07:05

In JBoss/WildFly, when configuring a data source, there is a JTA option, which is disabled by default:



        
3条回答
  •  星月不相逢
    2021-01-06 07:58

    Yes, of course you need to enable JTA on a datasource if you want to have jta transactions!

    Your XML/JBoss/Wildfly config file will look like this:

    In our webapp persistence-unit, the datasource looks like this:

    java:jboss/datasources/CoreDS
    

    The transaction-type="JTA" isn't necessary, at least not in my setup (Wildfly 8.1).

    In your Java code you can go like this to use transactions:

    @TransactionManagement(TransactionManagementType.CONTAINER) // class level
    public class ...
    ...
        @PersistenceContext(unitName = "CoreJPA")
        EntityManager em;
    
        @Resource
        private EJBContext ejbContext;
    ...
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) // method level
    public void doSomething(...)
    

    And if you need to rollback, you do this:

    try {
      ...
    } catch (Throwable t) {
        log.error("Exception in create work order: " + t.getMessage());
        ejbContext.setRollbackOnly();
        throw t;
    }
    

    There are a lot of resources about this that can be found using Google.

提交回复
热议问题