Spring与Dao-Jdbc模板实现对象的增删改查
IStudentDAOImpl .java
package com.hk.springdao.daoimpl; import java.util.List; import org.springframework.jdbc.core.support.JdbcDaoSupport; import com.hk.springdao.beans.Student; import com.hk.springdao.dao.IStudentDAO; public class IStudentDAOImpl extends JdbcDaoSupport implements IStudentDAO { @Override public void insertStudent(Student stu) { String sql = "insert into t_student(t_name,t_age) values(?,?)"; this.getJdbcTemplate().update(sql , stu.getName(),stu.getAge()); } @Override public void updateStudent(Student stu) { String sql = "update t_student set t_age= ?,t_name=? where t_id = ?"; this.getJdbcTemplate().update(sql , stu.getAge(),stu.getName(),stu.getId()); } @Override public void deleteStudent(int stuID) { String sql = "delete from t_student where t_id = ?;"; this.getJdbcTemplate().update(sql , stuID); } @Override public Student selectStuByStuID(int stuID) { String sql = "select * from t_student where t_id = ?"; return this.getJdbcTemplate().queryForObject(sql,new StudentRowMapper(),stuID); } @Override public List<Student> selectAllStudents() { String sql = "select * from t_student"; return this.getJdbcTemplate().query(sql, new StudentRowMapper()); } @Override public String selectStudentNameByID(int stuID) { String sql = "select t_name from t_student where t_id = ?"; return this.getJdbcTemplate().queryForObject(sql, String.class,stuID); } @Override public List<String> selectAllStuentNames() { String sql = "select t_name from t_student"; return this.getJdbcTemplate().queryForList(sql,String.class); } }
StudentRowMappe.java
package com.hk.springdao.daoimpl; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.hk.springdao.beans.Student; public class StudentRowMapper implements RowMapper<Student> { /** * rs 是结果集中的一条记录 */ @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setId(rs.getInt("t_id")); student.setAge(rs.getInt("t_age")); student.setName(rs.getString("t_name")); return student; } }