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 the org.springframework.jdbc.datasource.DriverManagerDataSource.
  • Set the credentials needed to the datasource, using the inherited methods setPassword(String password), setUrl(String url) and setUsername(String username) API methods of AbstractDriverBasedDataSource class, as also the setDriverClassName(String driverClassName) API method of DriverManagerDataSource. In the example, all above steps are performed in getDatasource() method.
  • Create a new JdbcTemplate object.
  • Invoke setDatasource(Datasource datasource) API method to set the DataSource 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();
	public static DriverManagerDataSource getDataSource() {

  DriverManagerDataSource dataSource = new DriverManagerDataSource();





  return dataSource;


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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button