
Using JDBCTemplate contd..
The following is the code for the java file which will use the JDBC Template. After getting the bean for the class we need to call the query method which will be used to execute the query on the database. The parameters which we pass in the method is the actual query, then the object array in case we need to pass the parameter like we use in preparedStatements and the rowmapper object in which we map the database resultset with the CustomerBean properties and making a new object to add it in the list.
package com.visualbuilder.DAO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public final class ExampleDAO {
public static void main(String[] args) throws Exception {
BeanFactory ctx = new ClassPathXmlApplicationContext(
"com/visualbuilder/DAO/bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
List customerList = jdbcTemplate.query("select id,name from customer",
new Object[0], new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum)
throws SQLException, DataAccessException {
CustomerBean cusomter = new CustomerBean();
cusomter.setId(rs.getString(1));
cusomter.setName(rs.getString(2));
return cusomter;
}
});
System.out.println("The retreived data is as follows:-");
for (int i = 0; i < customerList.size(); i++) {
CustomerBean cust = (CustomerBean) customerList.get(i);
System.out.println("ID is :- " + cust.getId());
System.out.println("Name is :- " + cust.getName());
}
}
}
Output:- The data gets printed as follows:-
The retreived data is as follows:-
ID is :- 1
Name is :- VisualBuilder
ID is :- 2
Name is :- John
Java Discussion
- - Difference between BMT an
- - Replace getParameterValue
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin



