JDBC 我们一定不陌生,刚开始学习的时候,我们写过很多很多重复的模板代码:

  1. public Student getOne(int id) {
  2. String sql = "SELECT id,name FROM student WHERE id = ?";
  3. Student student = null;
  4. // 声明 JDBC 变量
  5. Connection con = null;
  6. PreparedStatement ps = null;
  7. ResultSet rs = null;
  8. try {
  9. // 注册驱动程序
  10. Class.forName("com.myql.jdbc.Driver");
  11. // 获取连接
  12. con = DriverManager.getConnection("jdbc://mysql://localhost:" +
  13. "3306/student", "root", "root");
  14. // 预编译SQL
  15. ps = con.prepareStatement(sql);
  16. // 设置参数
  17. ps.setInt(1, id);
  18. // 执行SQL
  19. rs = ps.executeQuery();
  20. // 组装结果集返回 POJO
  21. if (rs.next()) {
  22. student = new Student();
  23. student.setId(rs.getInt(1));
  24. student.setName(rs.getString(1));
  25. }
  26. } catch (ClassNotFoundException | SQLException e) {
  27. e.printStackTrace();
  28. } finally {
  29. // 关闭数据库连接资源
  30. try {
  31. if (rs != null && !rs.isClosed()) {
  32. rs.close();
  33. }
  34. } catch (SQLException e) {
  35. e.printStackTrace();
  36. }
  37. try {
  38. if (ps != null && !ps.isClosed()) {
  39. ps.close();
  40. }
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. try {
  45. if (con != null && con.isClosed()) {
  46. con.close();
  47. }
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. return student;
  53. }

现在光是看着就头大,并且我还把它完整的写了出来..真恶心!

这还仅仅是一个 JDBC 的方法,并且最主要的代码只有ps = con.prepareStatement(sql);这么一句,而且有很多模板化的代码,包括建立连接以及关闭连接..我们必须想办法解决一下!

我想第一步我们可以把重复的模板代码提出来创建一个【DBUtil】数据库工具类:

  1. package util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. public class DBUtil {
  6. static String ip = "127.0.0.1";
  7. static int port = 3306;
  8. static String database = "student";
  9. static String encoding = "UTF-8";
  10. static String loginName = "root";
  11. static String password = "root";
  12. static {
  13. try {
  14. Class.forName("com.mysql.jdbc.Driver");
  15. } catch (ClassNotFoundException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. public static Connection getConnection() throws SQLException {
  20. String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip, port, database, encoding);
  21. return DriverManager.getConnection(url, loginName, password);
  22. }
  23. }

这样我们就可以把上面的恶心的代码变成这样:

  1. public Student getOne(int id) {
  2. String sql = "SELECT id,name FROM student WHERE id = ?";
  3. Student student = null;
  4. // 声明 JDBC 变量
  5. Connection con = null;
  6. PreparedStatement ps = null;
  7. ResultSet rs = null;
  8. try {
  9. // 获取连接
  10. con = DBUtil.getConnection();
  11. // 预编译SQL
  12. ps = con.prepareStatement(sql);
  13. // 设置参数
  14. ps.setInt(1, id);
  15. // 执行SQL
  16. rs = ps.executeQuery();
  17. // 组装结果集返回 POJO
  18. ....
  19. } catch (SQLException e) {
  20. e.printStackTrace();
  21. } finally {
  22. // 关闭数据库连接资源
  23. ....
  24. }
  25. return student;
  26. }

也只是少写了一句注册驱动程序少处理了一个异常而已,并没有什么大的变化,必须再优化一下

自动资源关闭是 JDK 7 中新引入的特性,不了解的同学可以去看一下我之前写的文章:JDK 7 新特性

于是代码可以进一步优化成这样:

  1. public Student getOne(int id) {
  2. String sql = "SELECT id,name FROM student WHERE id = ?";
  3. Student student = null;
  4. // 将 JDBC 声明变量包含在 try(..) 里将自动关闭资源
  5. try (Connection con = DBUtil.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) {
  6. // 设置参数
  7. ps.setInt(1, id);
  8. // 执行SQL
  9. ResultSet rs = ps.executeQuery();
  10. // 组装结果集返回 POJO
  11. if (rs.next()) {
  12. student = new Student();
  13. student.setId(rs.getInt(1));
  14. student.setName(rs.getString(1));
  15. }
  16. } catch (SQLException e) {
  17. e.printStackTrace();
  18. }
  19. return student;
  20. }

这样看着好太多了,但仍然不太满意,因为我们最核心的代码也就只是执行 SQL 语句并拿到返回集,再来再来

在 DBUtil 类中新增一个方法,用来直接返回结果集:

  1. public static ResultSet getResultSet(String sql, Object[] objects) throws SQLException {
  2. ResultSet rs = null;
  3. try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(sql)) {
  4. // 根据传递进来的参数,设置 SQL 占位符的值
  5. for (int i = 0; i < objects.length; i++) {
  6. ps.setObject(i + 1, objects[i]);
  7. }
  8. // 执行 SQL 语句并接受结果集
  9. rs = ps.executeQuery();
  10. }
  11. // 返回结果集
  12. return rs;
  13. }

这样我们就可以把我们最开始的代码优化成这样了:

  1. public Student getOne(int id) {
  2. String sql = "SELECT id,name FROM student WHERE id = ?";
  3. Object[] objects = {id};
  4. Student student = null;
  5. try (ResultSet rs = DBUtil.getResultSet(sql, objects);) {
  6. student.setId(rs.getInt(1));
  7. student.setName(rs.getString(1));
  8. } catch (SQLException e) {
  9. // 处理异常
  10. e.printStackTrace();
  11. }
  12. return student;
  13. }

wooh!看着爽多了,但美中不足的就是没有把 try-catch 语句去掉,我们也可以不进行异常处理直接把 SQLException 抛出去:

  1. public Student getOne(int id) throws SQLException {
  2. String sql = "SELECT id,name FROM student WHERE id = ?";
  3. Object[] objects = {id};
  4. Student student = null;
  5. try (ResultSet rs = DBUtil.getResultSet(sql, objects);) {
  6. student.setId(rs.getInt(1));
  7. student.setName(rs.getString(1));
  8. }
  9. return student;
  10. }

其实上面的版本已经够好了,这样做只是有些强迫症。

  • 我们自己定义的 DBUtil 工具已经很实用了,因为是从模板化的代码中抽离出来的,所以我们可以一直使用

要想使用 Spring 中的 JDBC 模块,就必须引入相应的 jar 文件:

  • 需要引入的 jar 包:
  • spring-jdbc-4.3.16.RELEASE.jar
  • spring-tx-4.3.16.RELEASE.jar

好在 IDEA 在创建 Spring 项目的时候已经为我们自动部署好了,接下来我们来实际在 Spring 中使用一下 JDBC:

就像我们创建 DBUtil 类,将其中连接的信息封装在里面一样,我们需要将这些数据库资源配置起来

  • 配置方式:
  • 使用简单数据库配置
  • 使用第三方数据库连接池

我们可以使用 Spring 内置的类来配置,但大部分时候我们都会使用第三方数据库连接池来进行配置,由于使用第三方的类,一般采用 XML 文件配置的方式,我们这里也使用 XML 文件配置的形式:

首先我们来试试 Spring 的内置类 org.springframework.jdbc.datasource.SimpleDriverDataSource

  1. <bean id="dateSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
  2. <property name="username" value="root"/>
  3. <property name="password" value="root"/>
  4. <property name="driverClass" value="com.mysql.jdbc.Driver"/>
  5. <property name="url" value="jdbc://mysql://locolhost:3306/student"/>
  6. </bean>

我们来测试一下,先把我们的 JDBC 操作类写成这个样子:

  1. package jdbc;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Component;
  4. import pojo.Student;
  5. import javax.sql.DataSource;
  6. import java.sql.*;
  7. @Component("jdbc")
  8. public class JDBCtest {
  9. @Autowired
  10. private DataSource dataSource;
  11. public Student getOne(int stuID) throws SQLException {
  12. String sql = "SELECT id, name FROM student WHERE id = " + stuID;
  13. Student student = new Student();
  14. Connection con = dataSource.getConnection();
  15. Statement st = con.createStatement();
  16. ResultSet rs = st.executeQuery(sql);
  17. if (rs.next()) {
  18. student.setId(rs.getInt("id"));
  19. student.setName(rs.getString("name"));
  20. }
  21. return student;
  22. }
  23. }

然后编写测试类:

  1. ApplicationContext context =
  2. new ClassPathXmlApplicationContext("applicationContext.xml");
  3. JDBCtest jdbc = (JDBCtest) context.getBean("jdbc");
  4. Student student = jdbc.getOne(123456789);
  5. System.out.println(student.getId());
  6. System.out.println(student.getName());

成功取出数据库中的数据:

上面配置的这个简单的数据源一般用于测试,因为它不是一个数据库连接池,知识一个很简单的数据库连接的应用。在更多的时候,我们需要使用第三方的数据库连接,比如使用 C3P0数据库连接池:

  1. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  2. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  3. <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
  4. <property name="user" value="root"></property>
  5. <property name="password" value="root"></property>
  6. <property name="initialPoolSize" value="3"></property>
  7. <property name="maxPoolSize" value="10"></property>
  8. <property name="maxStatements" value="100"></property>
  9. <property name="acquireIncrement" value="2"></property>
  10. </bean>

跟上面的测试差不多,不同的是需要引入相关支持 C3P0 数据库连接池的 jar 包而已。

Spring 中提供了一个 Jdbc Template 类,它自己已经封装了一个 DataSource 类型的变量,我们可以直接使用:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  10. <bean id="dataSrouce" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
  11. <property name="username" value="root"/>
  12. <property name="password" value="root"/>
  13. <property name="driverClass" value="com.mysql.jdbc.Driver"/>
  14. <property name="url" value="jdbc:mysql://localhost:3306/student"/>
  15. </bean>
  16. <context:component-scan base-package="jdbc" />
  17. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  18. <property name="dataSource" ref="dataSrouce"/>
  19. </bean>
  20. </beans>

我们来改写一下 JDBC 操作的类:

  1. package jdbc;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.jdbc.core.JdbcTemplate;
  4. import org.springframework.jdbc.core.RowMapper;
  5. import org.springframework.stereotype.Component;
  6. import pojo.Student;
  7. import java.sql.*;
  8. @Component("jdbc")
  9. public class JDBCtest {
  10. @Autowired
  11. private JdbcTemplate jdbcTemplate;
  12. public Student getOne(int stuID) throws SQLException {
  13. String sql = "SELECT id, name FROM student WHERE id = ?";
  14. Student student = jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
  15. @Override
  16. public Student mapRow(ResultSet resultSet, int i) throws SQLException {
  17. Student stu = new Student();
  18. stu.setId(resultSet.getInt("id"));
  19. stu.setName(resultSet.getString("name"));
  20. return stu;
  21. }
  22. }, 123456789);
  23. return student;
  24. }
  25. }

测试类不变,运行可以获得正确的结果:

但是好像并没有简单多少的样子,那我们来看看其他 CRUD 的例子:

  1. /**
  2. * 增加一条数据
  3. *
  4. * @param student
  5. */
  6. public void add(Student student) {
  7. this.jdbcTemplate.update("INSERT INTO student(id,name) VALUES(?,?)",
  8. student.getId(), student.getName());
  9. }
  10. /**
  11. * 更新一条数据
  12. *
  13. * @param student
  14. */
  15. public void update(Student student) {
  16. this.jdbcTemplate.update("UPDATE student SET name = ? WHERE id = ?",
  17. student.getName(), student.getId());
  18. }
  19. /**
  20. * 删除一条数据
  21. *
  22. * @param id
  23. */
  24. public void delete(int id) {
  25. this.jdbcTemplate.update("DELETE FROM student WHERE id = ?",
  26. id);
  27. }

现在应该简单多了吧,返回集合的话只需要稍微改写一下上面的 getOne() 方法就可以了

扩展阅读:官方文档Spring 中 JdbcTemplate 实现增删改查


  • 《Java EE 互联网轻量级框架整合开发》
  • 《Spring 实战》
  • 全能的百度和万能的大脑

扩展阅读:① 彻底理解数据库事务② Spring事务管理详解③ Spring 事务管理(详解+实例)④ 全面分析 Spring 的编程式事务管理及声明式事务管理


欢迎转载,转载请注明出处!
@我没有三颗心脏
CSDN博客:http://blog.csdn.net/qq939419061
简书:http://www.jianshu.com/u/a40d61a49221

版权声明:本文为wmyskxz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/wmyskxz/p/8845799.html