package com.spring.ch11.jdbctemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class DemoDaoImpl implements IDemoDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Demo getById(int id) {
return (Demo) this.jdbcTemplate.queryForObject(
"select id,name,unitPrice from demo d where d.id = ?",
new Integer[] { id }, demoRowMapper());
}
@Override
public List<Demo> getAll() {
return this.jdbcTemplate.query("select id,name,unitPrice from demo",
demoRowMapper());
}
private RowMapper demoRowMapper() {
return new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Demo demo = new Demo();
demo.setId(rs.getInt("id"));
demo.setName(rs.getString("name"));
demo.setUnitPrice(rs.getFloat("unitPrice"));
return demo;
}
};
}
}
Spring配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="placeHolder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:locations="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="com.spring.ch11.jdbctemplate.IDemoDao"
class="com.spring.ch11.jdbctemplate.DemoDaoImpl" p:dataSource-ref="dataSource">
</bean>
</beans>