Using JDBC for data access

Source: Internet
Author: User
Tags connection pooling error handling thread

The JDBC abstraction framework provided by spring consists of four different packages of core, datasource,object, and support.

As implied by its name, the Org.springframework.jdbc.core package defines a class that provides core functionality. There are various implementations of Sqlexceptiontranslator and Datafieldmaxvalueincrementer and a DAO base class for JdbcTemplate.

The Org.springframework.jdbc.datasource package has a tool class for simplifying data source access, and a simple implementation of various data sources to be used to test JDBC code without modification outside the Java container. This tool class provides a static method for obtaining a connection from Jndi and a closed connection that may be used. It supports binding thread connections, such as being used for Datasourcetransactionmanager.

Next, the Org.springframework.jdbc.object package is a class that encapsulates query, update, and stored procedures for relational databases into thread-safe and reusable objects. This simulates jdo, although the object returned by the query is naturally "detached" from the database connection. This JDBC high-level abstraction relies on the underlying abstraction implemented in the Org.springframework.jdbc.core package.

Finally, in the Org.springframework.jdbc.support package you can find SqlException conversion functions and some tool classes.

An exception thrown in a JDBC call is converted to an exception in the definition Org.springframework.dao package. This means that code that uses the spring JDBC Abstraction layer does not need to implement JDBC or RDBMS-specific error handling. All the converted exceptions are unchecked, which allows you to catch the exceptions you can recover and pass the rest of the exception to the caller.

JdbcTemplate

This is the most important class in the JDBC core package. It simplifies the use of JDBC because it handles the creation and release of resources. It helps you avoid some common mistakes, such as forgetting to close the connection. It runs core JDBC workflows, such as statement and execution, and requires only application code to provide SQL and extract results. This class executes the SQL query, updates or invokes the stored procedure, simulates the iteration of the result set, and extracts the return parameter values. It also captures JDBC exceptions and converts them into a generic system defined in the Org.springframework.dao package that can provide more information.

The code that uses this class only needs to implement the callback interface based on a well-defined set of contracts. The PreparedStatementCreator callback interface creates a PreparedStatement that is established by the connection provided by the class and provides SQL and any necessary parameters. Callablestatementcreateor implements the same processing, except that it creates a callablestatement. The RowCallbackHandler interface extracts values from each row of the dataset.

This class can be instantiated directly from a reference to a data source and then used in a service, or it can be generated in applicationcontext and used as a reference to a bean. Note: The data source should always be configured as a bean in ApplicationContext, the first of which is passed directly to the service and the second to JdbcTemplate. Because this class represents the callback interface and the Sqlexceptiontranslator interface as parameters, there is no need to define subclasses for it. All SQL executed by this class is logged.

Data source

To get the data from the database, we need to get a connection to the database. The approach that spring takes is through a data source. The data source is part of the JDBC specification and can be considered a generic connection factory. It allows the container or framework to hide the administrative operations of connection pooling and transactions in the application code. Developers will not need to know any details about connecting to the database, which is the responsibility of the administrator setting up the data source. Although you may need to play two roles while developing or testing, you do not need to know how the data source in the actual product is configured.

With the JDBC layer of spring, you can get a data source from Jndi, or you can configure it yourself by using the implementation provided by the spring release. The latter is very handy for unit testing that is detached from the Web container. We'll use the Drivermanagerdatasource implementation in this section, and of course we'll mention some other implementations later. Drivermanagerdatasource the same way as traditional ways to get a JDBC connection. In order for DriverManager to load the driver class, you must specify the JDBC driver complete class name. Then you must provide a different URL relative to the various JDBC drivers. You must refer to the driver document you are using to get the correct parameters to use. Finally, you must also provide a username and password to connect to the database The following example shows how to configure Drivermanagerdatasource:

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName( "org.hsqldb.jdbcDriver");
dataSource.setUrl( "jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername( "sa");
dataSource.setPassword( "");
10.2.3. SQLExceptionTranslator
SQLExceptionTranslator是一个需要实现的接口, 它被用来处理SQLException和我们的数据访问异常org.springframework.dao.DataAccessException之间的转换。

Implementations can be generic (such as using JDBC SQLState values), or they can be specialized for higher precision (such as using Oracle's ErrorCode).

Sqlerrorcodesqlexceptiontranslator is the implementation of Sqlexceptiontranslator, which is used by default. More accurate than vendor-specified sqlstate. ErrorCode conversions are based on values that are stored in the JavaBean of the sqlerrorcodes type. This class is created and populated by Sqlerrorcodesfactory, as its name suggests, Sqlerrorcodesfactory is based on a named "Sql-error-codes.xml" The contents of the configuration file set up Sqlerrorcodes's factory. This file is published with the vendor's code and is based on the databaseproductname in the DatabaseMetaData information, and the code suitable for the current database is used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.