Spring对JDBC的模板支持:JdbcTemplate(3)

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
    // 重写父类的setDataSource来设置数据源对象
    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;
    }

// 根据id进行删除
    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;
    }

// 根据id查询单行数据
    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也不错。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/265eb4bf8a115ed8c6e21d4d2707467d.html