Java & J2EE Page 4 - Data Access Using Spring Framework JDBC |
The application being developed will perform two functions. First, it will retrieve data related to a given ID. Second, it will delete the data related to a given ID. It is a simple application, but it will give you an idea of how JDBC and the Spring Framework work together. The application will have three main files:
Let us start with JdbcDataSource.java. It is same as the JdbcEventDao class. The following is the code: public class JdbcDataSource { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; }
public DataSource getDataSource() { return dataSource; } } Next comes the beans.xml. It contains the DataSource configuration as well as the bean configuration. <bean id="dataSource" destroy-method="close"
<property name="driverClassName"> <value> com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/requisition</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>sql</value> </property> </bean> <bean id="dao" class="JdbcDataSource"> <property name="dataSource"> <ref local="dataSource"/> </property> </bean> And at last we've reached the client. It takes command line arguments and, according to the first argument, either retrieves or deletes using the second argument as the ID. Here is the code. import java.io.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; import org.springframework.core.io.*; import org.springframework.jdbc.core.*; import org.springframework.jdbc.datasource.*; import org.springframework.jdbc.object.*; import org.springframework.jdbc.support.*; public class JdbcClient { public static void main(String args[]) throws Exception { try { Resource res = new ClassPathResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(res); JdbcDataSource bean = (JdbcDataSource)factory.getbean("dao"); JdbcTemplate template = new JdbcTemplate(bean.getDataSource());
if("select".equalsIgnoreCase(args[0])) { List list; list = template.queryForList("select * from indents where"+ Iterator i=list.iterator(); while(i.hasNext()) { Object ob = i.next(); out.println(ob.toString()); } }
if("delete".equalsIgnoreCase(args[0])) { template.execute("Delete from indents where indent_id ='" + }
}catch(Exception e) { } } } The delete functionality makes use of the execute method of the JdbcTemplate class. This method can be used to execute other SQL statements including inserts and updates. That completes this section as well as brings us to the end of this discussion. The approach discussed here is just one of the many approaches to using the Spring Framework's JDBC support. There are other approaches for the same. Those will be discussed in the future. Till then...
blog comments powered by Disqus |
|
|
|
|
|
|
|