Java Spring transaction management

Please excuse if this or a similar question has been asked before. I am new to Spring. My question is how is it that the transaction manager and the JdbcTemplate are using the same DB connection. In all the docs and books I could rely on, he said that a datasource is defined for beans (transaction manager and JDBC template). Let it be Apache Commons BasicDataSource. As far as I understand, both objects, when instantiated, will call the getConnection () method of the datasource and get different connections. This will update the JDBC template on one connection while the transaction manager commits on the other. Definitely no transactional behavior will happen.

Where am I going wrong?

My program is actually a little more complicated. It is multithreaded and manages connection pooling. Initially, each thread receives a "connection" (actually a JdbcTemplate object) and then uses it until finished. During its lifetime, it performs a series of "batch" database updates, which must be transactional. But trying to use @Transactional annotation fails - if there are two inserts in the batch and the second fails, then the first is not rolled back.

Both DataSourceTransactionManager and JdbcTemplate refer to the same BasicDataSource in beans.xml.

Obviously, somewhere I am terribly wrong in my understanding of the transaction management mecahism in Spring, because other people use it happily. But where is it?

+3


source to share


1 answer


You can actually look at the JdbcTemplate sources .

You can see that it does not receive connections directly from the datasource, but executes instead Connection con = DataSourceUtils.getConnection(getDataSource());

.



These DataSourceUtils are responsible for getting the current transaction connection from the Spring thread-local connection owner, or creating a new connection from the DataSource and registering it with the holder if this was the first request in a transaction, for example.

PS AND cannot handle single transactions across multiple threads with Spring's transaction engine in any convenient way.

0


source







All Articles