Java & J2EE Page 3 - Data Access Using Spring Framework JDBC |
Configuring the bean means providing a declaration for injecting the DataSource to the POJO or bean. It is done using the <ref> child tag of the <property> tag. The <ref> tag tells the Spring Framework that the current bean or POJO is referencing another bean. And the <property> tag tells the instance variable that it will receive the reference. For example, the following statements tell the Spring Framework that the bean with the ID "dao" refers the bean with the of ID"dataSource." The implementation of DataSource will be received by the DataSource instance variable within the JdbcEventDao class. The following is the code for the same: <bean id="dao" class=" JdbcEventDao "> <property name="dataSource"> <ref local="dataSource"/> </property> </bean> Finally, we are up to the third step, developing the client. To develop the client, you must do two things. First, you must retrieve an instance of the JdbcTemplate class. To do so, an implementation of DataSource needs to be retrieved using JdbcEventDao POJO. The following statements will retrieve the DataSource implementation as well as a JdbcTemplate instance: Resource res = new ClassPathResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(res); JdbcEventDao bean = (datacon)factory.getBean("dao"); DataSource ds=bean.getDataSource(); JdbcTemplate template = new JdbcTemplate(ds);
Second, the instance of the JdbcTemplate can be used to perform a CRUD (Insert, Select, Update, Delete) operation. For example, to retrieve all the records from "emp" table, the statement will be List list; list = template.queryForList("select * from emp"); The queryForList returns a list containing the values of the resultset. That brings us to the end of this section. In the next section, an application will be developed based on these steps.
blog comments powered by Disqus |
|
|
|
|
|
|
|