Search code examples
springjdbcjndispring-jdbc

Getting a JDBC connection by JNDI in Spring JDBC


This page on Spring JDBC says

The DataSourceUtils class … provides static methods to obtain connections from JNDI

However the API doc for DataSourceUtils does not include the said static methods, as far as I can see.

What am I missing?


Solution

  • Hmm... Somehow, the Javadoc of DataSourceUtils is more "accurate" (I mean, the doc is not wrong but technically, you obtain a connection from a DataSource - that can be obtained via JNDI):

    Helper class that provides static methods for obtaining JDBC Connections from a DataSource.

    And the following methods should be what you're looking for:

    Basic example (from the MySQL documentation):

    // Create a new application context. this processes the Spring config
    ApplicationContext ctx = new ClassPathXmlApplicationContext("ex1appContext.xml");
    // Retrieve the data source from the application context
    DataSource ds = (DataSource) ctx.getBean("dataSource");
    // Open a database connection using Spring's DataSourceUtils
    Connection c = DataSourceUtils.getConnection(ds);
    try {
        // retrieve a list of three random cities
        PreparedStatement ps = c.prepareStatement(
            "select City.Name as 'City', Country.Name as 'Country' " +
            "from City inner join Country on City.CountryCode = Country.Code " +
            "order by rand() limit 3");
        ResultSet rs = ps.executeQuery();
        while(rs.next()) {
            String city = rs.getString("City");
            String country = rs.getString("Country");
            System.out.printf("The city %s is in %s%n", city, country);
        }
    } catch (SQLException ex) {
        // something has failed and we print a stack trace to analyse the error
        ex.printStackTrace();
        // ignore failure closing connection
        try { c.close(); } catch (SQLException e) { }
    } finally {
        // properly release our connection
        DataSourceUtils.releaseConnection(c, ds);
    }