Java & J2EE Page 2 - Data Access Using Spring Framework JDBC |
Next let us see how to use Spring's JDBC support. Since JdbcTemplate is the 'lowest-level' of all the types, the steps required for JdbcTemplate become part of the steps for all other types. The following are the steps required to make use of JdbcTemplate: 1. Develop the bean 2. Configure the bean and DataSource 3. Develop the client Of these, the second and third steps can be divided into sub-steps. Here are the details. Develop the bean: The bean or POJO is similar to any other POJO used with the Spring Framework except for one difference. The POJO developed to be used with JdbcTemplate requires a setter for the DataSource object. The following is an example of a POJO that can be used with JdbcTemplate. The setter will pass the DataSource object to the instance of JdbcTemplate.
public class JdbcEventDao { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; }
public DataSource getDataSource() { return dataSource; } } The POJO can contain other methods that can work with the DataSource. Configure the DataSource and the bean: The configuration is done using the XML file. Lets call it beans.xml. This step can be further divided into configuring the DataSource, and configuring the bean. We will look at the DataSource first. <>A DataSource is configured by declaring it as a bean and providing the required information as the child nodes of the bean declaration. The configuration is done as follows: First, a bean is declared whose class is mapped to an implementation of <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> : : </bean> Second, the required details for the DataSource such as driver name, URL of the DataSource, credentials etc. can be passed onto the DataSource through property tags. The property tags are the children of the <bean> tag. In versions prior to 2.5, the property tags had the <value> tag as the child tag. For example, to pass "com.mysql.jdbc.Driver" as the value of a property named "driverClassName," the statement in version 2.5 and above will be <bean id="dataSource" destroy-method="close" </bean> and in previous versions it will be <bean id="dataSource" destroy-method="close" <property name="driverClassName"> <value> com.mysql.jdbc.Driver</value> </property> </bean> The next step is configuring the bean.
blog comments powered by Disqus |
|
|
|
|
|
|
|