2017-07-10 46 views
0

我正在使用spring jdbc。我正在使用下面的代碼來獲得jdbc連接如何訪問連接url

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

     } 
    } 

但我收到以下異常。

配置阻塞超時 (0 [毫秒])內沒有可用的管理的連接

我具有由調試代碼採取了打印。以上是getJdbcTemplate().getDataSource()代碼的輸出。

Click here for the image 如果我寫了getJdbcTemplate().getDataSource().getConnection();以下例外即將到來。如何訪問圖像中存在的 connectionURL。

配置阻塞超時時間內沒有可用的受管連接(0 [毫秒])

回答

0

您需要配置Spring上下文文件中的數據源與數據庫連接的詳細信息如下所示。

<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> 

而要訪問jdbcTemplate API,你需要注入你的java類。

@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()); 
    } 
} 

這將打印的你已經在Spring上下文文件中配置的數據源的URL(JDBC:MySQL的://本地主機:3306/TESTDB)