Reputation: 1906
I'm working on a project in which we are using spring jdbc template object which is declared in the bean. I want to create a jdbc template object to connect to another database and close that connection after some processing. I need jdbc template object since all our methods in DAO are taking jdbc template as a parameter to perform database operation. I can not declare another db connection in the spring bean since I need to connect to the second db for just one time processing whenever that service is called. Therefore I have to set jdbc template connection in java code and send that object to DAO methods to perform some processing into another DB.
Kindly help me with the code required to create jdbc template object in java code so that I can connect to db only when my service is called and close the connection afterwards.
Upvotes: 1
Views: 3439
Reputation: 1567
you can just define another JdbcTemplate
in your context config and autowire it in your service method:
<bean id="myJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="myDatasource" />
</bean>
<bean id="myDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
Inject this in your service class:
public class MyServiceClassImpl implements MyServiceClass {
@Autowired
@Qualifier("myJdbcTemplate") //if you have other defined JdbcTemplates
private JdbcTemplate myJdbcTemplate;
@Autowired
private MyDao dao;
public void myMethodThatCallsDao(){
dao.callMethod(myJdbcTemplate);
}
}
hope this helps.
Upvotes: 0
Reputation: 21923
Where ever you need the JdbcTemplate
for your one time access database. You can do the following code. Each Database vendor have their own specific implementation of Datasource which you can make use of.
for Derby, org.apache.derby.jdbc.ClientDataSource for MySQL, com.mysql.jdbc.jdbc2.optional.MysqlDataSource.
For example mysql database
DataSource dataSource = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
// Initialize the datasource with host, username, password
JdbcTemplate template = JdbcTemplate(dataSource);
// Use JdbcTemplate to access/modify database
Upvotes: 2