How to get dataSource for jdbc Connection in Spring

Connect with

Java datasource for Jdbc connection in spring

Java Datasource will be used to get JDBC connection in Spring java framework. There are a different ways of getting JDBC connection using DataSource in the java Spring framework and every approach has some meaning, so we should know where should be used what? and how this will be the best practices? Getting of DataSource is very easy in the Spring application framework.

1. Maven Dependency for java datasource

Spring JDBC dependency


 
     org.springframework
     spring-context
     4.0.2.RELEASE
  
  
     org.springframework
      spring-tx
      4.0.2.RELEASE
  
  
 
  
      org.springframework
      spring-jdbc
      4.0.2.RELEASE
  

Maven for MySql dependency to get datasource in java

 
     mysql
     mysql-connector-java
     5.0.5
 

DBCP DataSource dependency


	org.apache.commons
	commons-dbcp2
	2.1

2. Get Java Datasource using Driver Manager

We should use the DriverManagerDataSource class should only be used for testing purposes since it does not provide pooling and will perform poorly when multiple requests for a connection are made. Another best part for testing we do not need to add addition maven dependency like basicDataSource or c3po datasource.

Meta data Bean Configuration as:


    
    
    
    


  


Corresponding Java class configuration as:

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername("sa");
dataSource.setPassword("");

3. Get Datasource from DBCP configuration

Basic dataSource has capability to pool connection and it’s industry standard to use in the project.

XML bean configuration as :

 
        
        
        
        
    

4. Get datasource from C3PO Configuation

How to get java datasource and its XML bean configuration for C3PO configuration as follows and pull dependency from maven repository.


    
    
    
    




5. References

Spring Official site

Your suggestions are welcome to encourage us to write further. Happy Learning 🙂


Connect with

1 thought on “How to get dataSource for jdbc Connection in Spring”

  1. Pingback: Dinkar

Leave a Comment

Your email address will not be published. Required fields are marked *