How to run Queries in Spring framework
There is a large number of query methods supported by Spring framework.
For example see following code that converts returned JDBC Type to the Java class that is passed in as an argument.
Code:
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class QueryExample {
private JdbcTemplate jt;
private DataSource dataSource;
public int getCount() {
jt = new JdbcTemplate(dataSource);
int count = jt.queryForInt("select count(*) from person");
return count;
}
public String getName() {
jt = new JdbcTemplate(dataSource);
String name = (String) jt.queryForObject("select name from person", String.class);
return name;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}