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 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();
		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.

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button