Spring JdbcTemplate Select Query Examples
|
Spring »
On Feb 11, 2012 | { 2 Comments }
|
Tweet
|
Let us see how to use spring JdbcTemplate select query
Files Required
- SpringJdbcSelect.java
- OurLogic.java
- spconfig.xml
Directory Structure
![]() |
![]() |
SpringJdbcSelect.java
package java4s;
import java.util.Iterator;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
public class SpringJdbcSelect
{
JdbcTemplate jt;
public void setJt(JdbcTemplate jt)
{
this.jt = jt;
}
public void loadAll()
{
List l = jt.queryForList("select * from countries");
Iterator it = l.iterator();
while(it.hasNext())
{
Object o = it.next();
System.out.println(o.toString());
}
}
}
OurLogic.java
package java4s;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class OurLogic
{
public static void main(String args[])
{
Resource res = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
SpringJdbcSelect jt =(SpringJdbcSelect)factory.getBean("id3");
jt.loadAll();
}
}
spconfig.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="id1" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/> <property name="username" value="system"/> <property name="password" value="admin"/> </bean> <bean id="id2" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg> <ref bean="id1"/> </constructor-arg> </bean> <bean id="id3" class="java4s.SpringJdbcSelect"> <property name="jt"> <ref bean="id2"/> </property> </bean> </beans>
Output:
![]() |
![]() |
Explanation
See the xml file.. actually our beam is id3, which needs JdbcTemplate to use the methods so i have given <ref bean=”id2″/>, and JdbcTemplate(id2) class need DriverManagerDataSource help so i have given <ref bean=”id1“/>, hope you got it.
|
What you are thinkig....
2 Responses to “Spring JdbcTemplate Select Query Examples”
If you want a pic to show with your comment, go get a gravatar !
Please post your questions on Java4s Answers forum





In SpringJdbcSelect.java instead of iterating the list trough Iterator its better to use for-each loop then code will be like
public void loadAll()
{
List l = jt.queryForList(“select * from countries”);
for (Object o : l)
System.out.println(o.toString());
}
}
@Raja
Yeah we can use either Iterator or Foreach, actually its depends, will not possible in all the cases