声明:本栏目所使用的素材都是凯哥学堂VIP学员所写,学员有权匿名,对文章有最终解释权;凯哥学堂旨在促进VIP学员互相学习的基础上公开笔记。 通过JdbcTemplate来编写一个简单的增删查改小例题:接口: package org.zero01.dao;
import org.zero01.pojo.Student;
import java.util.List;
public interface DAO {
public int insert(Student student);
public int delete(int sid);
public List<Student> selectAll();
public List<Student> selectByLimit(int start, int end);
public Student selectById(int sid);
public long countAll();
public int update(Student student);
}
因为JdbcTemplate不提供表格字段自动映射到对象的属性上的功能,所以我们需要自己实现它的一个接口来进行手动配置映射: package org.zero01.dao;
import org.springframework.jdbc.core.RowMapper;
import org.zero01.pojo.Student;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student student = new Student();
student.setSid(resultSet.getInt("sid"));
student.setName(resultSet.getString("sname"));
student.setAge(resultSet.getInt("age"));
student.setSex(resultSet.getString("sex"));
student.setAddress(resultSet.getString("address"));
return student;
}
}
StudentDAO类: package org.zero01.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.zero01.pojo.Student;
import javax.sql.DataSource;
import java.util.List;
@Component("stuDAO")
public class StudentDAO extends JdbcTemplate implements DAO {
@Autowired
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
}
public int insert(Student student) {
String sql = "INSERT INTO student(sname,age,sex,address) VALUES (?,?,?,?)";
int row = update(sql, student.getName(), student.getAge(), student.getSex(), student.getAddress());
return row;
}
public int delete(int sid) {
return update("DELETE FROM student WHERE sid=?", sid);
}
public List<Student> selectAll() {
List<Student> studentList = query("SELECT * FROM student", new StudentMapper());
return studentList;
}
public List<Student> selectByLimit(int start, int end) {
List<Student> studentList = query("SELECT * FROM student LIMIT " + start + "," + end, new StudentMapper());
return studentList;
}
public Student selectById(int sid) {
Object[] objects = {sid};
Student student = queryForObject("SELECT * FROM student where sid=?", objects, new StudentMapper());
return student;
}
public long countAll() {
Long countNumber = queryForObject("SELECT count(*) FROM student", Long.class);
return countNumber;
}
public int update(Student student) {
String sql = "UPDATE student SET sname=?,age=?,sex=?,address=? WHERE sid=?";
return update(sql, student.getName(), student.getAge(), student.getSex(), student.getAddress(), student.getSid());
}
}
如上,可以看到,通过使用Spring提供的JdbcTemplate,我们只需要编写具体的sql语句即可,比起编写普通的JDBC代码要简洁许多,也没有出现多余的代码。当项目不需要使用到Mybatis、Hibernate等框架时,使用JdbcTemplate也不错。 |