Spring 支持三种数据访问技术
JDBC操作 -------- JdbcTemplate
Hibernate框架操作 -------- HibernateTemplate
IBatis 框架操作 -------- SqlMapClientTemplate
JdbcTemplate 使用和 Apache DBUtils 非常类似
导入jar包 : 6个Spring最基本jar包 、spring-jdbc 、spring-tx 、数据库驱动
1、 手动JdbcTemplate 编程
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); // 连接池
// 设置四个基本连接参数
driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql:///spring3day2");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("abc");2、使用配置文件 开发JdbcTemplate (将连接池配置到文件中 )配置DBCP 导入
com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar com.springsource.org.apache.commons.pool-1.5.3.jar配置c3p0 导入
com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar3、 使用applicationContext.xml 配置数据库连接基本参数,XML格式文件维护起来不是很方便
在applicationContext.xml <context:property-placeholder> 引入一个外部properties 文件
<!-- 引入一个外部 properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 第三种 c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <T> T query(String sql, ResultSetExtractor<T> rse, Object... args) 查询 ----------------- 完整封装过程
List<User> users = jdbcTemplate.query("select * from user", new ResultSetExtractor<List<User>>(){
@Override
public List<User> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<User> users = new ArrayList<User>();
while(rs.next()){
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
users.add(user);
}
return users;
}
});
<T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) 查询 ------------ 只负责对象本身封装过程
List<User> users = jdbcTemplate.query("select * from user", new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
return user;
}
});class UserDAO extends JdbcDaoSupport {
}<!-- Spring核心监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
原文地址:http://blog.csdn.net/u012815721/article/details/40143309