Deep analysis of Spring architecture and design principles-operation implementation of database

Source: Internet
Author: User
Tags assert stmt

about Spring JDBC
Let's start with spring JDBC, although many of the applications are now using Hibernate or other ORM tools directly. But JDBC is still very basic, in which the jdbctemplate is often used, such as JdbcTemplate's Execute method, is a basic method, in the implementation of this method, you can see the basic process of database operation.


The Execute method executes the input SQL statement
public void execute (final String sql) throws DataAccessException {
if (logger.isdebugenabled ()) {
Logger.debug ("Executing SQL statement [" + SQL + "]");
}
Class Executestatementcallback implements Statementcallback<object>, SQLProvider {
Public Object doinstatement (Statement stmt) throws SQLException {
Stmt.execute (SQL);
return null;
}
Public String GetSQL () {
return SQL;
}
}
Execute (New Executestatementcallback ());
}
This is a way to handle static SQL statements using Java.sql.Statement
Public <T> T Execute (statementcallback<t> action) throws DataAccessException {
Assert.notnull (Action, "Callback object must not is null");
This gets the connection of the database, the connection of the database is already under Spring's transaction management
Connection con = datasourceutils.getconnection (Getdatasource ());
Statement stmt = null;
try {
Connection contouse = con;
if (this.nativejdbcextractor! = null &&
This.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements ()) {
Contouse = This.nativeJdbcExtractor.getNativeConnection (con);
}
Create statement
stmt = Contouse.createstatement ();
Applystatementsettings (stmt);
Statement stmttouse = stmt;
if (this.nativejdbcextractor! = null) {
Stmttouse = This.nativeJdbcExtractor.getNativeStatement (stmt);
}
Call the callback function here
T result = Action.doinstatement (stmttouse);
Handlewarnings (stmt);
return result;
}
catch (SQLException ex) {
Release Connection early, to avoid potential Connection pool deadlock
In the case when the exception translator hasn ' t been initialized yet.
If you catch a database exception, release the database connection and throw a spring-converted spring Database exception
Spring does a meaningful job of unifying these databases into its own anomaly system.
Jdbcutils.closestatement (stmt);
stmt = null;
Datasourceutils.releaseconnection (Con, Getdatasource ());
con = null;
Throw Getexceptiontranslator (). Translate ("Statementcallback", GetSQL (Action), ex);
}
finally {
Jdbcutils.closestatement (stmt);
Releasing the database connection
Datasourceutils.releaseconnection (Con, Getdatasource ());
}
}


In the use of the database, there is a very important place is the management of the database connection, here, is done by the datasourceutils. Spring uses this helper class to manage the connection of data. For example, it can be done to open and close connection and other operations. Datasourceutils the implementation of these database connection management, as shown in the following code.


This is the call to get the database connection, the implementation is done by calling Dogetconnection, where the exception conversion operation is performed
public static Connection getconnection (DataSource DataSource) throws Cannotgetjdbcconnectionexception {
try {
Return dogetconnection (DataSource);
}
catch (SQLException ex) {
throw new Cannotgetjdbcconnectionexception ("Could not get JDBC Connection", ex);
}
}
public static Connection dogetconnection (DataSource DataSource) throws SQLException {
Assert.notnull (DataSource, "No dataSource specified");
The connection of the database is managed in transaction management, where the threadlocal variables defined in Transactionsynchronizationmanager are used to connect to the thread-bound database
If the database connection is already bound to the current thread in Transactionsynchronizationmanager, then it is taken directly to use
Connectionholder Conholder = (connectionholder) transactionsynchronizationmanager.getresource (DataSource);
if (Conholder! = null && (conholder.hasconnection () | | conholder.issynchronizedwithtransaction ())) {
Conholder.requested ();
if (!conholder.hasconnection ()) {
Logger.debug ("Fetching resumed JDBC Connection from DataSource");
Conholder.setconnection (Datasource.getconnection ());
}
return Conholder.getconnection ();
}
Else we either got no holder or an empty thread-bound holder here.
Here you get the required database connection, defined in the Bean configuration file,
Finally, the newly opened database connection is bound by Transactionsynchronizationmanager and the current thread.
Logger.debug ("Fetching JDBC Connection from DataSource");
Connection con = datasource.getconnection ();

if (transactionsynchronizationmanager.issynchronizationactive ()) {
Logger.debug ("Registering transaction synchronization for JDBC Connection");
Use same Connection for further JDBC actions within the transaction.
Thread-bound object would get removed by synchronization at transaction completion.
Connectionholder holdertouse = Conholder;
if (Holdertouse = = null) {
Holdertouse = new Connectionholder (con);
}
else {
Holdertouse.setconnection (con);
}
Holdertouse.requested ();
Transactionsynchronizationmanager.registersynchronization (
New Connectionsynchronization (Holdertouse, DataSource));
Holdertouse.setsynchronizedwithtransaction (TRUE);
if (holdertouse! = Conholder) {
Transactionsynchronizationmanager.bindresource (DataSource, holdertouse);
}
}
return con;
}


about database operations class RDBMS
From JdbcTemplate, we see that he offers a lot of simple query and update functionality. However, if you need a higher level of abstraction and a more object-oriented approach to accessing the database, Spring provides us with the Org.springframework.jdbc.object package, which contains the sqlquery, Sqlmappingquery, Classes such as Sqlupdate and StoredProcedure, which are available to spring JDBC applications. Note, however, that these classes need to be configured with JdbcTemplate as their basic operational implementation, because in their functional implementations, the implementation of the database operation is largely dependent on the jdbctemplate.

For example, the process of using the mappingsqlquery is very concise, after the design of the data mapping code, the query has been converted to the previous design of the object list, a query record corresponding to a data object, The database can be mapped directly into Java objects used in the program, but also avoid the use of third-party ORM tool configuration, for simple data mapping occasions is very convenient, in the implementation of the Maprow method to provide data conversion rules, and we use Hibernate, Hibernate's HBM files play a very similar role. This mappingsqlquery needs to compile the settings, and these compile are done as shown in the following code:


Protected final void compileinternal () {
Here is the compile process for the parameters, all of which are inside the getdeclaredparameters, generating a preparedstatementcreatorfactory
This.preparedstatementfactory = new PreparedStatementCreatorFactory (GetSQL (), getdeclaredparameters ());
This.preparedStatementFactory.setResultSetType (Getresultsettype ());
This.preparedStatementFactory.setUpdatableResults (Isupdatableresults ());
This.preparedStatementFactory.setReturnGeneratedKeys (Isreturngeneratedkeys ());
if (getgeneratedkeyscolumnnames () = null) {
This.preparedStatementFactory.setGeneratedKeysColumnNames (Getgeneratedkeyscolumnnames ());
}
His.preparedStatementFactory.setNativeJdbcExtractor (Getjdbctemplate (). Getnativejdbcextractor ());
Oncompileinternal ();
}


When executing a query, it is actually the SQLQuery Executebynamedparam method that needs to be done, including configuring the SQL statement, configuring the data logging to the RowMapper of the data object's transformation, Then use JdbcTemplate to complete the query of the data and start the conversion of the data record to the Java data object, as shown in the following code:


Public list<t> Executebynamedparam (map<string,?> Parammap, Map context) throws DataAccessException {
Validatenamedparameters (PARAMMAP);
Get the SQL statement you want to execute
Parsedsql parsedsql = Getparsedsql ();
Mapsqlparametersource Paramsource = new Mapsqlparametersource (PARAMMAP);
String sqltouse = Namedparameterutils.substitutenamedparameters (Parsedsql, Paramsource);
Configure the SQL statements required by the parameters and RowMapper, this rowmapper complete data logging to object conversion
object[] params = Namedparameterutils.buildvaluearray (Parsedsql, Paramsource, Getdeclaredparameters ());
rowmapper<t> RowMapper = Newrowmapper (params, context);
We see JdbcTemplate again, here we use JdbcTemplate to complete the query operation on the database, so we say JdbcTemplate is very basic operation class
Return getjdbctemplate (). Query (Newpreparedstatementcreator (sqltouse, params), rowmapper);
}


In the operation of the spring for JDBC, it is basically the encapsulation of the API based on the jdbc/hibernate. These packages can be used directly or configured in the IOC container, and when used on the basis of an IOC container, you can see that many of the processing parts related to transaction management are well worth learning, where you can see the management of the data source- Hibernate session management, the combination of threads and so on.

For more information, please follow the public number: it haha (it_haha)

650) this.width=650; "style=" Width:auto;height:auto; "src=" http://mmbiz.qpic.cn/mmbiz_jpg/ Xruic8oiyw5upuvcv1cifldft9jiazjawtzuqviaytibsdh5le8ricktou2mn0iblkxzw5kgo4ntibmclfng97qyqsntq/640?wx_fmt=jpeg &wxfrom=5&wx_lazy=1 "alt=" 640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1 "/>


This article is from the "doujh" blog, make sure to keep this source http://doujh.blog.51cto.com/10177066/1933904

In-depth analysis of spring architecture and design principles-operational implementation of the database

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.