-->

In JBoss/WildFly should I enable JTA on data sourc

2020-03-04 12:22发布

问题:

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

<datasource jta="false" jndi-name="java:/wt/testds" pool-name="testds" enabled="true" use-ccm="false">  
...  
</datasource> 

Now I want to associate this data source with JPA using JTA transaction type:

<?xml version="1.0" encoding="UTF-8"?>  
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"  
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">  
    <persistence-unit name="test" transaction-type="JTA">  
        <jta-data-source>java:/wt/testds</jta-data-source>  
    </persistence-unit>  
</persistence>  

Do I also need to enable JTA on the data source?

回答1:

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:

<datasource jta="true" ...

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

<jta-data-source>java:jboss/datasources/CoreDS</jta-data-source>

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.



回答2:

I've just experienced a problem related to this issue.

I was running a container managed transaction involving approximately 20,000 inserts into a MySQL database.

The transaction failed randomly, sometimes after around 3,500 inserts, other times after around 6,000 inserts, etc.

After investigation I found that the JTA option on the WildFly datasource definition was set to false.

Changing this setting to true fixed the problem, so I would agree with @user3472929 that JTA should be set to true in the datasource definition unless you have some specific reason not to.



回答3:

I think you should use jta. And if you set jta to false in the container configuration file, jta will be disabled for JPA, so the transaction-type for JPA will be "RESOURCE_LOCAL", which has some nasty side effect. By the way, jta is true in the container configuration file by default.