数据库中的数据表:
create table client
(
clientId int identity(1,1),
clientName varchar(100)
)
创建返回对象类:
public class client
{
private Integer clientId;
private String clientName;
public client()
{
}
public Integer getClientId() {
return this.clientId;
}
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
public String getClientName() {
return this.clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
}
使用spring的jdbcTemplate查询返回对象
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("bean.xml"));
org.springframework.jdbc.core.JdbcTemplate template = (org.springframework.jdbc.core.JdbcTemplate) factory.getBean("jdbcTemplate");
java.util.List<client> list = (java.util.List<hbconfig.client>)template.query(
"select * from client", new ResultSetExtractor() {
public Object extractData(ResultSet arg0)
throws SQLException, DataAccessException {
java.util.List<hbconfig.Client> list = new java.util.ArrayList<Client>();
while (arg0.next()) {
client c = new client();
c.setClientId(arg0.getInt("clientId"));
c.setClientName(arg0.getString("clientName"));
list.add(c);
}
return list;
}
});
for(hbconfig.Client c : list)
{
System.out.println(c.getClientName());
}
bean.xml配置信息
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byName">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wangfu"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>