spring整合JDBC
spring提供了很多模板整合Dao技术
其中JdbcTemplate封装了JDBC技术,其与DBUtils中的QueryRunner非常相似.
与Web结合步骤:
1、导包
4+2
spring-test
spring-aop
junit4类库
c3p0连接池
JDBC驱动
spring-jdbc
spring-tx事务
2、书写Dao
获取JdbcTemplate对象的方法
方式一:
继承JdbcDaoSupport类,使用super.getJdbcTemplate()获取
public class UserDaoImpl extends JdbcDaoSupport implements UserDao{ // private JdbcTemplate jt; // public void setJt(JdbcTemplate jt) { // this.jt = jt; // } @Override public void save(User u) { String sql = "insert into user values (null,?) "; super.getJdbcTemplate().update(sql,u.getName()); } @Override public void delete(Integer id) { String sql = "delete from user where id=?"; super.getJdbcTemplate().update(sql,id); } @Override public void update(User u) { String sql = "update user set name=? where id=?"; super.getJdbcTemplate().update(sql,u.getName(),u.getId()); } @Override public User getById(Integer id) { String sql = "select * from user where id=?"; User u = super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>() { @Override public User mapRow(ResultSet resultSet, int i) throws SQLException { User u = new User(); u.setId(resultSet.getInt("id")); u.setName(resultSet.getString("name")); return u; } }, id); return u; } @Override public int getTotalCount() { String sql = "select count(*) from user"; Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class); return count; } @Override public List<User> getAll() { String sql = "select * from user"; List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>() { @Override public User mapRow(ResultSet resultSet, int i) throws SQLException { User u = new User(); u.setId(resultSet.getInt("id")); u.setName(resultSet.getString("name")); return u; } }); return list; } }