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?
Three Java technologies that still use JNDI are JDBC, EJB, and JMS.
JPA Configuration – Model, DAO and Service. With this, you have everything you need in order to use your JNDI datasource in your Spring application.
As I understand, what would be really useful to you is JndiObjectFactoryBean. This Spring factory bean returns object published in JNDI.
You would configure it like this, and then you would get the Connection
using DataSourceUtils
on the injected DataSource
:
<bean name="myDataSourceInJndi" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/MyDataSource</value>
</property>
</bean>
<bean name="myBean" class="MyClass">
...
<property name="dataSource" ref="myDataSourceInJndi">
...
</bean>
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:
DataSourceUtils.getConnection(DataSource)
DataSourceUtils.getGetConnection(DataSource)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With