How do you determine if a JDBC connection has been connected to this DataSource JTA or direct JDBC?

I am using the provider API to get the JDBC connection to the application database. The API works when running on the application server or when working offline. I want to run a series of SQL statements in a single transaction. I am fine with them arising in the context of a JTA transaction, if one exists. However, if this is not the case, I need to use JDBC transaction demarcation methods. (Calling these methods on a JDBC connection participating in a JTA transaction raises a SQLException.)

So, I need to determine if the connection is connected to this DataSource enabled by the JTA, or if it is just a direct JDBC connection.

Is there a direct way to make this determination?

Thanks!

+4
source share
3 answers

Even if it is direct JDBC, you can enable the JTA transaction. Checking the autoCommit flag will NOT help in this regard. You may be in a transaction, distributed or otherwise, with autoCommit set to false. autoCommit set to true will tell you that you are not in a distributed transaction, but false means that you will not automatically commit ... it can be in any transaction.

I think you will have to call UserTransaction.getStatus () and make sure it is not equal to Status.NoTransaction (). This will tell you if you have a JTA transaction.

+4
source

What tylo says makes sense.

Otherwise, I’m not sure directly, BUT I will give you a “hack” way

write BAD SQL, which, as you know, will give a DB exception. This will lead to a stack trace. From the stack trace, you can find out if this is a JTA derivative or NOT?

0
source

You can try checking the Connection autoCommit checkbox to see if it is in the transaction (regardless of where it came from). Strike> (Apparently, see the accepted answer, this does not work too well. I do not delete this answer because the following remains :)

But I think that you really need to change your API so that it depends only on external transactions. If you still want to support simple JDBC, wrap it in a separate API that is just starting the transaction.

Update. Just re-read your question and make sure you are not providing an API, but want to use a container-driven connection. But still, can you simply instruct (as part of your application requirements) that the JTA will act? If not, you can provide a configuration option to revert to manual transactions. For such a critical function, it seems reasonable to require the correct configuration (as opposed to trying to guess what would be appropriate).

-1
source

Source: https://habr.com/ru/post/1277548/


All Articles