本系列博客汇总在这里:Spring 汇总
jdbcTemplate
jdbcTemplate源码工程文件为:spring3.2_10
1、第一步:引入 jdbc 的包
2、第二步:配置数据源
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring3.2_10"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<!-- 初始化的连接数 -->
<property name="initialSize" value="1"></property>
<!-- 连接池的最大连接数-->
<property name="maxActive" value="5"></property>
<!-- 最大的空闲的连接数 -->
<property name="maxIdle" value="2"></property>
<!-- 最小的空闲连接数 -->
<property name="minIdle" value="1"></property>
</bean>
3、第三步:建立 t_user 表
4、第四步:DAO
public class UserDaoImpl implements UserDao
{
private DataSource dataSource;
private JdbcTemplate jt;
public void setDataSource(DataSource dataSource)
{
this.dataSource = dataSource;
this.jt = new JdbcTemplate(dataSource);
}
@Override
public void saveUser(User user)
{
String sql = "insert into t_user values(null, ?, ?)";
jt.update(sql, new Object[]{user.getUsername(), user.getPassword()});
}
@Override
public void updateUser(User user)
{
String sql = "update t_user set username = ?, password=? where user_id = ?";
jt.update(sql, new Object[]{user.getUsername(), user.getPassword(), user.getUserId()});
}
@Override
public User queryUserById(int userId)
{
String sql = "select * from t_user t where t.user_id = ?";
User user = jt.queryForObject(sql, new Object[]{userId}, new UserRowMapper());
return user;
}
@Override
public List<User> queryUserAll()
{
String sql = "select * from t_user";
List<User> userList = jt.query(sql, new UserRowMapper());
return userList;
}
}
如有错误,欢迎指正!