Oracle 5.0 Reference Manual page 2128

Table of Contents

Advertisement

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
The focus in the above code is on the
country code and use the
placed in a Map with the key "country", which is the parameter is named in the SQL query.
To access this code, you need to configure it with Spring by providing a reference to the data source.
<bean id="dao" class="code.Ex2JdbcDao">
<property name="dataSource" ref="dataSource"/>
</bean>
At this point, we can just grab a reference to the DAO from Spring and call
getRandomCityByCountryCode().
// Create the application context
ApplicationContext ctx =
new ClassPathXmlApplicationContext("ex2appContext.xml");
// Obtain a reference to our DAO
Ex2JdbcDao dao = (Ex2JdbcDao) ctx.getBean("dao");
String countryCode = "USA";
// Find a few random cities in the US
for(int i = 0; i < 4; ++i)
System.out.printf("A random city in %s is %s%n", countryCode,
This example shows how to use Spring's JDBC classes to completely abstract away the use of
traditional JDBC classes including
20.3.13.2. Transactional JDBC Access
You might be wondering how we can add transactions into our code if we do not deal directly with
the JDBC classes. Spring provides a transaction management package that not only replaces JDBC
transaction management, but also enables declarative transaction management (configuration instead
of code).
To use transactional database access, we will need to change the storage engine of the tables in
the world database. The downloaded script explicitly creates MyISAM tables which do not support
transactional semantics. The InnoDB storage engine does support transactions and this is what we will
be using. We can change the storage engine with the following statements.
ALTER TABLE City ENGINE=InnoDB;
ALTER TABLE Country ENGINE=InnoDB;
ALTER TABLE CountryLanguage ENGINE=InnoDB;
A good programming practice emphasized by Spring is separating interfaces and implementations.
What this means is that we can create a Java interface and only use the operations on this interface
without any internal knowledge of what the actual implementation is. We will let Spring manage the
implementation and with this it will manage the transactions for our implementation.
First you create a simple interface:
public interface Ex3Dao {
Integer createCity(String name, String countryCode,
String district, Integer population);
}
This interface contains one method that will create a new city record in the database and return the id
of the new record. Next you need to create an implementation of this interface.
Using Connector/J with Spring
NamedParameterJdbcTemplate
dao.getRandomCityByCountryCode(countryCode));
Connection
getRandomCityByCountryCode()
and PreparedStatement.
2108
method. We pass a
to query for a city. The country code is

Advertisement

Table of Contents
loading

This manual is also suitable for:

Mysql 5.0

Table of Contents