讨论一个问题,以下这是一段常见的往数据库写入数据的JDBC代码:
public int jdbcInsert(Student student) throws SQLException {
Connection connection = null;
try {
connection = dataSource.getConnection();
String sql = "INSERT INTO student(sname,age,sex,address) VALUES (?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, student.getName());
preparedStatement.setInt(2, student.getAge());
preparedStatement.setString(3, student.getSex());
preparedStatement.setString(4, student.getAddress());
return preparedStatement.executeUpdate();
} finally {
connection.close();
}
}
问题:
重复的不易于维护和修改,而且写起来还累
所以Spring提供的JdbcTemplate正是用来解决这个问题的
dbcTemplate在实际开发中一般不会使用,通常都是使用Mybatis、Hibernate等成熟、优秀的数据持久层框架,不过还是得知道Spring有一个这样的jdbc模板类。
Spring对不同的持久化支持: