One concern in this method is, since it starts and end transactions per HTTP request, will it increase the number of database connections and disconnections. Well there is a possibility and it will reduce the overall performance of the system.
As described in Class DataSourceTransactionManager it is a good idea to create a database connection when it is actually needed for example only when executing a SQL statement. In this way a dummy transaction will be started but it will not create a database connection. The connection will be established only when it is needed during the transaction.
Extract from the class documentation
"Consider defining a LazyConnectionDataSourceProxy
for your target DataSource, pointing both this transaction manager and your DAOs to it. This will lead to optimized handling of "empty" transactions, i.e. of transactions without any JDBC statements executed. A LazyConnectionDataSourceProxy will not fetch an actual JDBC Connection from the target DataSource until a Statement gets executed, lazily applying the specified transaction settings to the target Connection."
So we will define LazyConnectionDataSourceProxy based on a usual datasource. Then transaction manager as well as our JdbcTemplate will be pointed to this LazyConnectionDataSource as below.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Creating TransactionManager Bean, since JDBC we are creating of type | |
DataSourceTransactionManager --> | |
<bean id="transactionManager" | |
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> | |
<property name="dataSource" ref="lazyConnectionDatasourceProxy" /> | |
</bean> | |
<!-- Lazy creation of database connections--> | |
<bean id="lazyConnectionDatasourceProxy" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy"> | |
<property name="targetDataSource" ref="dataSource"/> | |
</bean> | |
<!-- JNDI actual datasource --> | |
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/myDS" expected-type="javax.sql.DataSource"/> | |
<!-- Definition for JDBCTemplate bean --> | |
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> | |
<property name="dataSource" ref="lazyConnectionDatasourceProxy" /> | |
</bean> |
Now JdbcTemplate as well as the Transaction manager will grab a database connection only when it is actually needed.