JDBC
Create Data Source for JdbcTemplate
This is an example of how to create a Datasource
for the JdbcTemplate
class provided by the Spring Framework. The DataSource
class is a utility class that provides connection to the database. It is part of the JDBC specification and allows a container or a framework to hide connection pooling and transaction management issues from the application code. Creating a Datasource implies that you should:
- Create a new object using a class that implements the
Datasource
interface. Here we use theorg.springframework.jdbc.datasource.DriverManagerDataSource.
- Set the credentials needed to the datasource, using the inherited methods
setPassword(String password)
,setUrl(String url)
andsetUsername(String username)
API methods ofAbstractDriverBasedDataSource
class, as also thesetDriverClassName(String driverClassName)
API method ofDriverManagerDataSource
. In the example, all above steps are performed ingetDatasource()
method. - Create a new
JdbcTemplate
object. - Invoke
setDatasource(Datasource datasource)
API method to set theDataSource
to obtain connections from.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.enterprise; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class CreateDataSourceForJdbcTemplate { private static final String driverClassName = "com.mysql.jdbc.Driver"; private static final String url = "jdbc:mysql://localhost/companydb"; private static final String dbUsername = "jcg"; private static final String dbPassword = "jcg"; private static DataSource dataSource; public static void main(String[] args) throws Exception { dataSource = getDataSource(); // JdbcTemplate template = new JdbcTemplate(dataSource); // constructor JdbcTemplate template = new JdbcTemplate(); template.setDataSource(dataSource); System.out.println(dataSource.getClass()); } public static DriverManagerDataSource getDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(dbUsername); dataSource.setPassword(dbPassword); return dataSource; } }
Output:
class org.springframework.jdbc.datasource.DriverManagerDataSource
This was an example of how to create a Datasource
for the JdbcTemplate
class provided by the Spring Framework.