JdbcTemplate Study (i)

Source: Internet
Author: User

Overview

The Spring JDBC Abstract Framework Core package provides the JDBC template class, where JdbcTemplate is the core class of a core package, so other template classes are based on its encapsulation, and the JDBC template class is the first mode of operation.

The JdbcTemplate class helps us eliminate lengthy code by using template design patterns, doing only what we need to do (i.e., variable parts), and doing some fixed parts for us, such as creating and closing connections.

The JdbcTemplate class implements a callback interface for the mutable part, such as Connectioncallback to return a connection to the user via a callback interface, so that the connection can be used to do anything, Statementcallback returns a statement to the user via a callback interface, which can be used to do anything, and so on, and some other callback interfaces

In addition to providing the JdbcTemplate core class, Spring provides a namedparameterjdbctemplate class based on the JdbcTemplate implementation to support named parameter bindings, The Simplejdbctemplate class is used to support variable parameters of java5+ and automatic packing and unpacking.

Callback classes supported by the JdbcTemplate class:

    • Precompiled statements and stored procedure creation callbacks: Used to create the corresponding statements based on the connection provided by the JdbcTemplate;

PreparedStatementCreator: A callback Gets the connection provided by the JdbcTemplate, which is used by the user to create the relevant preparedstatement;

CallableStatementCreator: A callback Gets the connection provided by the JdbcTemplate, which is used by the user to create the relevant callablestatement;

    • Pre-compiled statement set value callback: used to set the corresponding parameters of the precompiled statement;

PreparedStatementSetter: JdbcTemplate provided by the callback to obtain the PreparedStatement, by the user to the corresponding pre-compiled statements corresponding parameters set values;

BatchPreparedStatementSetter:; similar to PreparedStatementSetter, but for batch processing, you need to specify batch size;

    • Custom Function Callback: Provides the user with an extension point where the user can perform any number of required operations at the specified type of extension point;

Connectioncallback: The jdbctemplate provided by the callback gets the connection, the user can perform any number of operations in the connection;

Statementcallback: The jdbctemplate provided by the callback gets the statement, the user can perform any number of operations in the statement;

PreparedStatementCallback: The jdbctemplate provided by the callback gets the PreparedStatement, the user can perform any number of operations in the PreparedStatement;

CallableStatementCallback: The jdbctemplate provided by the callback gets the CallableStatement, the user can perform any number of operations in the CallableStatement;

    • Result set processing callback: processing resultset through callbacks or converting resultset to the desired form;

RowMapper: Used to convert a result set per row of data to a desired type, the user implements the method Maprow (ResultSet rs, int rowNum) to complete converting each row of data to the appropriate type.

RowCallbackHandler: For each row of the ResultSet, the user implements the method Processrow (ResultSet RS) to complete the processing, eliminating the need to perform rs.next () in the callback method, The operation is performed by JdbcTemplate and the user simply fetches the data by row and then processes it.

ResultSetExtractor: For the result set data extraction, the user needs to implement the method Extractdata (ResultSet RS) to process the result set, the user must process the entire result set;

The following is a detailed explanation of Jdbctmeplate's crud operations:

(i) Increased operation:

1) Add, update, delete a piece of data (SQL fixed, no parameters required):

(a) int update (final String SQL)

Where the SQL parameter is an inserted SQL statement that needs to be passed in.

(b) int update (PreparedStatementCreator psc)

     Public void Test () {        jdbctemplate.update (new  PreparedStatementCreator () {                        @Override              Public PreparedStatement createpreparedstatement (Connection conn)                     throws SQLException {                return conn.preparestatement ("INSERT into test (name) VALUES (' name1 ')" );               }        });    }

(c) If you need to return the primary key for the newly inserted data, use the following method ( using Keyholder keyholder=new generatedkeyholder (); Get the primary key, Both JdbcTemplate and Namedparameterjdbctemplate can obtain the primary key by this method :

int update (PreparedStatementCreator psc, final keyholder generatedKeyHolder)

 Public voidTest () {Keyholder keyholder=NewgeneratedKeyHolder (); Jdbctemplate.update (NewPreparedStatementCreator () {@Override PublicPreparedStatement createpreparedstatement (Connection conn)throwsSQLException {returnConn.preparestatement ("INSERT into test (name) VALUES (' name1 ')");        }},keyholder); inti = Keyholder.getkey (). Intvalue ();//This is the primary key for the data you just inserted.}

2) Add, update, delete a piece of data (SQL needs to inject parameter fill '? ’):

(a) int update (String sql, PreparedStatementSetter pss)

 public  void   Test () {String sql  = "INSERT into test (name) VALUES (?)"        ;  //  Returns the number of rows updated  int  count = jdbctemplate.update (sql, new   PreparedStatementSetter () {@Override  public  void   Setvalues (  PreparedStatement pstmt)  throws               SQLException {pstmt.setobject ( 1, "Name4" 

(b) int update (String sql, object[] args, int[] argtypes)

The parameter meaning: SQL: Preprocessing SQL statement; Args:sql needs to be injected, argtypes: The JDBC type of SQL parameter to be injected (java.sql.Types to get the constant of type );

     Public void Test () {        = "INSERT INTO Test (name,age,create_date) VALUES (?,?,?)" ;         New Date (System.currenttimemillis ());         // returns the number        of rows that were updated int New New int []{types.varchar,types.integer,types.date});    }

(c) int update (String sql, Object ... args)

In fact, internal or call method a implementation, JdbcTemplate provides this more simple way "update (String sql, Object ... args)" To achieve the set value, Therefore, you should use PreparedStatementSetter (above method a) only if you do not meet the requirements in this way.

 Public void Test () {        = "INSERT INTO Test (name,age,create_date) VALUES (?,?,?)" ;         New Date (System.currenttimemillis ());         // returns the number        of rows that were updated int count = jdbctemplate.update (sql, "Xiaoming", +, now);    }
 Public void Test () {        = "INSERT INTO Test (name,age,create_date) VALUES (?,?,?)" ;         New Date (System.currenttimemillis ());         // returns the number        of rows that were updated int New object[]{"Xiao Ming", (+), now    });

These two actually call the method, so that Object...args is actually a mutable array, and the array length is fixed, you must first define an array, and Object...args at the time of passing the arguments can be arbitrary, so you can also pass a fixed object array.

(d) int update (PreparedStatementCreator psc)

Use this method to add, delete, update operations by using the original JDBC approach to the precompiled SQL injection parameters:

JdbcTemplate Study (i)

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.