Springjdbc 简明教程

Spring JDBC - Overview

在使用普通旧 JDBC 处理数据库时,编写不必要的代码来处理异常、打开和关闭数据库连接等会变得麻烦。但是,Spring JDBC 框架负责所有底层详细信息,从打开连接、准备和执行 SQL 语句、处理异常、处理事务,到最后关闭连接。

While working with database using plain old JDBC, it becomes cumbersome to write unnecessary code to handle exceptions, opening and closing database connections, etc. However, Spring JDBC Framework takes care of all the low-level details starting from opening the connection, preparing and executing the SQL statement, processing exceptions, handling transactions, and finally closing the connection.

您要做的只是定义连接参数并指定要执行的 SQL 语句,以及在从数据库获取数据时为每次迭代执行所需的工作。

What you have do is just define connection parameters and specify the SQL statement to be executed and do the required work for each iteration while fetching data from the database.

Spring JDBC 提供了几种方法,相应地提供了不同的类来与数据库进行交互。在本教程中,我们将采用经典且最流行的方法,即使用框架的 JDBC 模板类。这是管理所有数据库通信和异常处理的中心框架类。

Spring JDBC provides several approaches and correspondingly different classes to interface with the database. In this tutorial, we will take classic and the most popular approach which makes use of JDBC Template class of the framework. This is the central framework class that manages all the database communication and exception handling.

JDBC Template Class

JDBC 模板类执行 SQL 查询、更新语句和存储过程调用,执行 ResultSets 迭代,并提取返回的参数值。它还捕获 JDBC 异常,并将它们转换为 org.springframework.dao 包中定义的通用、信息更丰富的异常层次结构。

JDBC Template class executes SQL queries, updates statements and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.

一旦 JDBC 模板类的实例配置好,它们就是线程安全的。因此,您可以配置 JDBC 模板的单个实例,然后安全地将这个共享引用注入多个 DAO。

Instances of the JDBC Template class are threadsafe once configured. So, you can configure a single instance of a JDBC Template and then safely inject this shared reference into multiple DAOs.

在使用 JDBC 模板类时,一种常见做法是在 Spring 配置文件中配置一个 DataSource,然后将该共享 DataSource bean 依赖项注入 DAO 类。JDBC 模板是在 DataSource 的 setter 中创建的。

A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes. The JDBC Template is created in the setter for the DataSource.

Data Access Object (DAO)

DAO 表示 Data Access Object ,通常用于数据库交互。DAO 存在于提供一种方式,用于读写数据库数据,并且应该通过一个接口公开此功能,应用程序的其余部分将通过该接口访问这些数据。

DAO stands for Data Access Object which is commonly used for database interaction. DAOs exist to provide a means to read and write data to the database and they should expose this functionality through an interface by which the rest of the application will access them.

Spring 中的数据访问对象 (DAO) 支持使得以一致的方式使用诸如 JDBC、Hibernate、JPA 或 JDO 之类的数据访问技术变得容易。

The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies such as JDBC, Hibernate, JPA, or JDO in a consistent way.