How to get dataSource for jdbc Connection in Spring

Connect with

Spring Framework

There are different way of getting DataSource in Spring 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 Spring application framework.

1. Maven Dependency

  • 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
      
     
  • for MySql dependency
  •  
         mysql
         mysql-connector-java
         5.0.5
     
    
  • DBCP DataSource dependency
  • 
    	org.apache.commons
    	commons-dbcp2
    	2.1
    
    

    2. By using Driver Manager Data Source

    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. DBCP configuration

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

    XML bean configuration as :

     
            
            
            
            
        
    

    4. C3PO Configuation

    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 Reply

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