开发者

JDBCTemplate with TransactionTemplate and Connection Pool, which datasource to use

开发者 https://www.devze.com 2023-04-01 10:37 出处:网络
I\'m not quite sure how to formulate the question, so feel free to tell me that I am thinking completly wrong.

I'm not quite sure how to formulate the question, so feel free to tell me that I am thinking completly wrong.

I want to use the JdbcTemplate and the TransactionTemplate. I start of by initilizing my connection pool as datasource and the create a transaction manager as a datasource aswell?

        BoneCPConfig connectionPoolConfig = new BoneCPConfig();
    connectionPoolConfig.setJdbcUrl(...);
    connectionPoolConfig.setUsername(...); 
    connectionPoolConfig.setPassword(...);
    connectionPoolConfig.setMinConnectionsPerPartition(...);
    connectionPoolConfig.setMaxConnectionsPerPartition(...);
    dataSource = new BoneCPDataSource(connectionPoolConfig);
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
    transactionManager.setDataSource(dataSource);

But now I want to create my TransactionTemplate and JdbcTemplate:

transactionTemplate = new TransactionTemplate(transactionManager);
JdbcTemplate jdbc = new JdbcTemplate(transactionManager.getDataSource());
开发者_StackOverflow

Now mulitple threads access transactionTemplate and jdbc. Does this code guarantee that everything done in doInTransaction uses the same connection for all jdbc calls?

Is the connection somehow linked internally, because it looks as if JdbcTemplate and TransactionTemplate could use what ever connection they wanted. Is my code correct/save?


This should all be fine. The critical part is that JdbcTemplate and DataSourceTransactionManager are supplied with the same DataSource object, which you have done.

Does this code guarantee that everything done in doInTransaction uses the same connection for all jdbc calls? Is the connection somehow linked internally, because it looks as if JdbcTemplate and TransactionTemplate could use what every connection they wanted.

Internally, Spring uses complex transaction synchronization logic to make sure that the transactions, connections and datasources are all properly synchronized (if you're interested, have a look at TransactionSynchronizationManager, although be warned, it's fearsome).

As long as you operate via the TransactionTemplate and JdbcTemplate APIs, it'll just work without any effort on your part. If you start manually fetching connections from the DataSource yourself, though, then all bets are off.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号