Rakesh
Rakesh

Reputation: 41

How to access connection url

I am using spring jdbc. I am using the following code to get jdbc connection

public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
        setJdbcTemplate(new JdbcTemplate(this.dataSource));
        setNamedParamdbcTemplate(new NamedParameterJdbcTemplate(this.dataSource));
        if(connectionUrl==null){
        Connection con;

            try {
                con = getJdbcTemplate().getDataSource().getConnection();
                connectionUrl = con.getMetaData().getURL();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

But I am getting the following exception.

No managed connections available within configured blocking timeout (0 [ms])

I Have took the print by debugging the code. the above is the output for getJdbcTemplate().getDataSource() code.

Click here for the image If I wrote getJdbcTemplate().getDataSource().getConnection();the following exception is coming. How can I access the connectionURL That is present in the image.

No managed connections available within configured blocking timeout (0 [ms])

Upvotes: 1

Views: 5676

Answers (1)

bpetlur
bpetlur

Reputation: 383

You need to configure the DataSource in spring context file as shown below with your Database connection details.

   <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/testDB" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean> 

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

And to access the jdbcTemplate API , you need to inject in your java classes.

@Repository
public class EmployeeDAO{

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public List<Emplyee> getEmployeeList(){
    //If you want to print the connection URL in your method
     System.out.println("Connection URL: "+ jdbcTemplate.getDataSource().getConnection().getMetaData().getURL());
  }
}

This will print the your DataSource URL which your have configured in spring context file (jdbc:mysql://localhost:3306/testDB)

Upvotes: 2

Related Questions