使用JBDC进行数据访问外文翻译资料

 2022-08-14 02:08

15.Data access with JDBC

15.1 Introduction to Spring Framework JDBC

The value-add provided by the Spring Framework JDBC abstraction is perhaps best shown by the sequence of actions outlined in the table below. The table shows what actions Spring will take care of and which actions are the responsibility of you, the application developer.

Table 15.1. Spring JDBC - who does what?

The Spring Framework takes care of all the low-level details that can make JDBC such a tedious API to develop with.

Choosing an approach for JDBC database access

You can choose among several approaches to form the basis for your JDBC database access. In addition to three flavors of the JdbcTemplate, a new SimpleJdbcInsert and SimplejdbcCall approach optimizes database metadata, and the RDBMS Object style takes a more object-oriented approach similar to that of JDO Query design. Once you start using one of these approaches, you can still mix and match to include a feature from a different approach. All approaches require a JDBC 2.0-compliant driver, and some advanced features require a JDBC 3.0 driver.

bull; JdbcTemplate is the classic Spring JDBC approach and the most popular. This 'lowest level' approach and all others use a JdbcTemplate under the covers.

bull; NamedParameterJdbcTemplate wraps a JdbcTemplate to provide named parameters instead of the traditional JDBC '?' placeholders. This approach provides better documentation and ease of use when you have multiple parameters for an SQL statement.

bull;SimpleJdbcInsert and SimpleJdbcCall optimize database metadata to limit the amount of necessary configuration. This approach simplifies coding so that you only need to provide the name of the table or procedure and provide a map of parameters matching the column names. This only works if the database provides adequate metadata. If the database doesnrsquo;t provide this metadata, you will have to provide explicit configuration of the parameters.

bull; RDBMS Objects including MappingSqlQuery, SqlUpdate and StoredProcedure requires you to create reusable and thread-safe objects during initialization of your data access layer. This approach is modeled after JDO Query wherein you define your query string, declare parameters, and compile the query. Once you do that, execute methods can be called multiple times with various parameter values passed in.

Package hierarchy

The Spring Frameworkrsquo;s JDBC abstraction framework consists of four different packages, namely core, datasource, object, and support.

The org.springframework.jdbc.core package contains the JdbcTemplate class and its various callback interfaces, plus a variety of related classes. A subpackage named org.springframework.jdbc.core.simple contains the SimpleJdbcInsert and SimpleJdbcCall classes. Another subpackage named org.springframework.jdbc.core.namedparam contains the NamedParameterJdbcTemplate class and the related support classes. See Section 15.2, “Using the JDBC core classes to control basic JDBC processing and error handling”, Section 15.4, “JDBC batch operations”, and Section 15.5, “Simplifying JDBC operations with the SimpleJdbc classes”. The org.springframework.jdbc.datasource package contains a utility class for easy DataSource access, and various simple DataSource implementations that can be used for testing and running unmodified JDBC code outside of a Java EE container. A subpackage named org.springfamework.jdbc.datasource.embedded provides support for creating embedded databases using Java database engines such as HSQL, H2, and Derby. See Section 15.3, “Controlling database connections” and Section 15.8, “Embedded database support”.

The org.springframework.jdbc.object package contains classes that represent RDBMS queries, updates, and stored procedures as thread-safe, reusable objects. See Section 15.6, “Modeling JDBC operations as Java objects”. This approach is modeled by JDO, although objects returned by queries are naturally disconnected from the database. This higher level of JDBC abstraction depends on the lower-level abstraction in the org.springframework.jdbc.core package.

The org.springframework.jdbc.support package provides SQLException translation functionality and some utility classes. Exceptions thrown during JDBC processing are translated to exceptions defined in the org.springframework.dao package. This means that code using the Spring JDBC abstraction layer does not need to implement JDBC or RDBMS-specific error handling. All translated exceptions are unchecked, which gives you the option of catching the exceptions from which you can recover while allowing other exceptions to be propagated to the caller. See the section called “SQLExceptionTranslator”.

15.2Using the JDBC core classes to control basic JDBC processing and error handling

JdbcTemplate

The JdbcTemplate class is the central class in the JDBC core package. It handles the creation and release of resources, which helps you avoid common errors such as forgetting to close the connection. It performs the basic tasks of the core JDBC workflow such as statement creation and execution, leaving application code to provide SQL and extract results. The JdbcTemplate class executes SQL queries, update 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.

When you use the JdbcTemplate for your code, you only need to implement callback interfaces, giving them a clearly defined contract. The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class, providing SQL and any necessary parameters. The same is

剩余内容已隐藏,支付完成后下载完整资料


15.使用JBDC进行数据访问

15.1Spring Framework JDBC简介

Spring JDBC抽象框架所带来的价值可能最好由下表中概述的操作序列来显示。该表显示了哪些操作Spring将处理,哪些操作是应用程序开发人员的责任。

Table 15.1. Spring JDBC - who does what?

Spring将替我们完成所有使用JDBC API进行开发的单调乏味的、底层细节处理工作。

选择一种JDBC数据库访问的方法

使用Spring进行基本的JDBC访问数据库有多种选择。Spring至少提供了三种不同的工作模式:JdbcTemplate, 一个在Spring2.5中新提供的SimpleJdbc类能够更好的处理数据库元数据; 还有一种称之为RDBMS Object的风格的面向对象封装方式, 有点类似于JDO的查询设计。 我们在这里简要列举你采取某一种工作方式的主要理由. 不过请注意, 即使你选择了其中的一种工作模式, 你依然可以在你的代码中混用其他任何一种模式以获取其带来的好处和优势。 所有的工作模式都必须要求JDBC 2.0以上的数据库驱动的支持, 其中一些高级的功能可能需要JDBC 3.0以上的数据库驱动支持。

bull;JdbcTemplate这是经典的也是最常用的Spring对于JDBC访问的方案。这也是最低级别的封装, 其他的工作模式事实上在底层使用了JdbcTemplate作为其底层的实现基础。JdbcTemplate在JDK 1.4以上的环境上工作得很好。

bull; NamedParameterJdbcTemplate对JdbcTemplate做了封装,提供了更加便捷的基于命名参数的使用方式而不是传统的JDBC所使用的“?”作为参数的占位符。这种方式在你需要为某个SQL指定许多个参数时,显得更加直观而易用。该特性必须工作在JDK 1.4以上。

bull;SimpleJdbcInsert和SimpleJdbcCall这两个类可以充分利用数据库元数据的特性来简化配置。通过使用这两个类进行编程,你可以仅仅提供数据库表名或者存储过程的名称以及一个Map作为参数。其中Map的key需要与数据库表中的字段保持一致。这两个类通常和SimpleJdbcTemplate配合使用。这两个类需要工作在JDK 5以上,同时数据库需要提供足够的元数据信息。

bull;RDBMS对象包括MappingSqlQuery,SqlUpdate and StoredProcedure这种方式允许你在初始化你的数据访问层时创建可重用并且线程安全的对象。该对象在你定义了你的查询语句,声明查询参数并编译相应的Query之后被模型化。一旦模型化完成,任何执行函数就可以传入不同的参数对之进行多次调用。这种方式需要工作在JDK 1.4以上。

SpringJDBC包结构

Spring Framework的JDBC抽象框架由四个包构成:core、 dataSource、object以及support。

org.springframework.jdbc.core包由JdbcTemplate类以及相关的回调接口(callback interface)和类组成。 org.springframework.jdbc.core.simple 子包则包含了 SimpleJdbcTemplate 类以及相关的SimpleJdbcInsert 类和SimpleJdbcCall 类。 org.springframework.jdbc.core.namedparam 子包则包含了NamedParameterJdbcTemplate 类以及其相关的支持类。

org.springframework.jdbc.datasource包提供了一些工具类来简化对DataSource的访问。同时提供了多种简单的DataSource实现。这些实现可以脱离J2EE容器进行独立测试和运行。 这些工具类提供了一些静态方法,允许你通过JNDI来获取数据库连接和关闭连接。同时支持绑定到当前线程的数据库连接。例如使用DataSourceTransactionManager。

接着org.springframework.jdbc.object包包含了一些类,用于将RDBMS查询、更新以及存储过程表述为一些可重用的、线程安全的对象。这种方式通过JDO进行模型化,不过这些通过查询返回的对象是与数据库脱离的对象。 这种对于JDBC的高层次的封装是基于org.springframework.jdbc.core包对JDBC的低层次封装之上的。

最后,org.springframework.jdbc.support包定义了SQLException转化类以及一些其他的工具类。

在JDBC调用过程中所抛出的异常都会被转化为在org.springframework.dao包中定义的异常。也就是说,凡是使用Spring的JDBC封装层的代码无需实现任何JDBC或者RDBMS相关的异常处理。所有的这些被转化的异常都是unchecked异常,因而也给了你一种额外的选择,你可以抓住这些异常,从而转化成其他类型的异常被允许调用者传播。

15.2利用JDBC核心类控制JDBC的基本操作和错误处理

JdbcTemplate类

JdbcTemplate是core包的核心类。它替我们完成了资源的创建以及释放工作,从而简化了我们对JDBC的使用。 它还可以帮助我们避免一些常见的错误,比如忘记关闭数据库连接。 JdbcTemplate将完成JDBC核心处理流程,比如SQL语句的创建、执行,而把SQL语句的生成以及查询结果的提取工作留给我们的应用代码。 它可以完成SQL查询、更新以及调用存储过程,可以对ResultSet进行遍历并加以提取。 它还可以捕获JDBC异常并将其转换成org.springframework.dao包中定义的,通用的,信息更丰富的异常。

使用JdbcTemplate进行编码只需要根据明确定义的一组契约来实现回调接口。PreparedStatementCreator回调接口通过给定的Connection创建一个PreparedStatement,包含SQL和任何相关的参数。CallableStatementCreateor实现同样的处理,只不过它创建的是CallableStatement。RowCallbackHandler接口则从数据集的每一行中提取值。

我们可以在DAO实现类中通过传递一个DataSource引用来完成JdbcTemplate的实例化,也可以在Spring的IoC容器中配置一个JdbcTemplate的bean并赋予DAO实现类作为一个实例。 需要注意的是DataSource在Spring的IoC容器中总是配制成一个bean,第一种情况下,DataSourcebean将传递给service,第二种情况下DataSource bean传递给JdbcTemplatebean。

最后,JdbcTemplate中使用的所有SQL将会以DEBUG级别记入日志(一般情况下日志的category是JdbcTemplate相应的全限定类名,不过如果需要对JdbcTemplate进行定制的话,可能是它的子类名)。

NamedParameterJdbcTemplate类

NamedParameterJdbcTemplate类为JDBC操作增加了命名参数的特性支持,而不是传统的使用(?)作为参数的占位符。NamedParameterJdbcTemplate类对JdbcTemplate类进行了封装, 在底层,JdbcTemplate完成了多数的工作。这一个章节将主要描述NamedParameterJdbcTemplate类与JdbcTemplate类的一些区别,也就是使用命名参数进行JDBC操作。

// some JDBC-backed DAO class...

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource)

{

this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

}

public int countOfActorsByFirstName(String firstName)

{

String sql = 'select count(*) from T_ACTOR where first_name = :first_name';

SqlParameterSource namedParameters = new MapSqlParameterSource('first_name', firstName);

return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);

}

注意这里在sql中使用了命名参数作为变量,而这个名称所对应的值被定义在传入的namedParameters中作为参数(也可以传入到MapSqlParameterSource中作为参数)。

你也可以传入许多命名参数以及他们所对应的值,以Map的方式,作为键值对传入到NamedParameterJdbcTemplate中(其余的被NamedParameterJdbcOperations所暴露的接口以及NamedParameterJdbcTemplate实现类遵循了类似的方式,此处不包含相关内容)。

或者可以使用基于Map的样式将命名参数及其相应值传递给命名参数JDBC模板实例。 由命名参数JDBC操作和由命名参数JDBC模板类实现的其余方法遵循类似的模式,这里不包括。

下面的示例显示了基于Map的样式的使用。

/// some JDBC-backed DAO class...

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource){

this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

}

public int countOfActorsByFirstName(String firstName) {

String sql = 'select count(*) from T_ACTOR where first_name = :first_name';

Map namedParameters = Collections<stro

剩余内容已隐藏,支付完成后下载完整资料</stro


资料编号:[235620],资料为PDF文档或Word文档,PDF文档可免费转换为Word

原文和译文剩余内容已隐藏,您需要先支付 30元 才能查看原文和译文全部内容!立即支付

以上是毕业论文外文翻译,课题毕业论文、任务书、文献综述、开题报告、程序设计、图纸设计等资料可联系客服协助查找。