In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
About Spring JDBC
Let's start with Spring JDBC, although many applications now use Hibernate or other ORM tools directly. But after all, JDBC is still very basic, in which JdbcTemplate is often used, such as JDBCTemplate's execute method, is a basic method, in the implementation of this method, we 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, SqlProvider {
Public Object doInStatement (Statement stmt) throws SQLException {
Stmt.execute (sql)
Return null
}
Public String getSql () {
Return sql
}
}
Execute (new ExecuteStatementCallback ())
}
/ / this is the way to use java.sql.Statement to handle static SQL statements
Public T execute (StatementCallback action) throws DataAccessException {
Assert.notNull (action, "Callback object must not be null")
/ / get the Connection of the database here, and the Connection of this database is already under the transaction management of Spring
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 a Statement
Stmt = conToUse.createStatement ()
ApplyStatementSettings (stmt)
Statement stmtToUse = stmt
If (this.nativeJdbcExtractor! = null) {
StmtToUse = this.nativeJdbcExtractor.getNativeStatement (stmt)
}
/ / callback function is called 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 a database exception is caught, release the database Connection and throw a Spring-converted Spring database exception
/ / Spring has done a meaningful work, which is to unify these databases into its own exception system.
JdbcUtils.closeStatement (stmt)
Stmt = null
DataSourceUtils.releaseConnection (con, getDataSource ())
Con = null
Throw getExceptionTranslator () .translate (StatementCallback, getSql (action), ex)
}
Finally {
JdbcUtils.closeStatement (stmt)
/ / release database connection
DataSourceUtils.releaseConnection (con, getDataSource ())
}
}
When using the database, there is a very important place is the management of database connections, here, is completed by DataSourceUtils. Spring manages the Connection of the data through this helper class. For example, it can be used to open and close Connection and other operations. DataSourceUtils implements the Connection management of these databases, as shown in the following code.
/ / this is the call to get the database connection, and the implementation is accomplished by calling doGetConnection, where the abnormal 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")
/ / put the Connection of the database into transaction management, where the ThreadLocal variable defined in TransactionSynchronizationManager is used to bind the database connection to the thread
/ / if you already have a database connection bound to the current thread in TransactionSynchronizationManager, just take it out and use it.
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.
/ / get the required database Connection here, which is defined in the Bean configuration file
/ / at the same time, bind the newly opened database Connection to the current thread through TransactionSynchronizationManager.
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 will 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 the database operation class RDBMS
From JdbcTemplate, we can see that it provides a lot of simple query and update capabilities. However, if a higher level of abstraction and a more object-oriented approach are needed to access the database, Spring provides us with the org.springframework.jdbc.object package, which contains classes such as SqlQuery, SqlMappingQuery, SqlUpdate, and StoredProcedure that can be used by Spring JDBC applications. Note, however, that when using these classes, you need to configure JdbcTemplate for them as their basic operational implementation, because in their functional implementation, that part of the implementation of database operations is basically dependent on JdbcTemplate.
For example, the process of using MappingSqlQuery is very concise. After designing the data mapping code, the records obtained by the query have been transformed into object List according to the previous design. A query record corresponds to a data object, which can be directly mapped to Java objects in the database and can be used in the program. At the same time, the configuration of third-party ORM tools can be avoided, which is very convenient for simple data mapping. The data conversion rules provided in the implementation of the mapRow method are very similar to the role of Hibernate's hbm file when we use Hibernate. The MappingSqlQuery needs to compile the settings, and the compile is done like this, as shown in the following code:
Protected final void compileInternal () {
/ / here is the compile procedure for the parameters. All the parameters are in the getDeclaredParameters and a PreparedStatementCreatorFactory is generated.
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 the query, what is actually executed is the executeByNamedParam method of SqlQuery, which requires configuring the SQL statement, configuring the RowMapper of the conversion of data logging to the data object, then using JdbcTemplate to complete the query of the data, and starting the transformation of the data record to the Java data object, as shown in the following code:
Public List executeByNamedParam (Map paramMap, Map context) throws DataAccessException {
ValidateNamedParameters (paramMap)
/ / get the SQL statement to be executed
ParsedSql parsedSql = getParsedSql ()
MapSqlParameterSource paramSource = new MapSqlParameterSource (paramMap)
String sqlToUse = NamedParameterUtils.substituteNamedParameters (parsedSql, paramSource)
/ / configure the Parameters and rowMapper required by the SQL statement. This rowMapper completes the conversion of data records to objects.
Object [] params = NamedParameterUtils.buildValueArray (parsedSql, paramSource, getDeclaredParameters ())
RowMapper rowMapper = newRowMapper (params, context)
/ / We see JdbcTemplate again. Here we use JdbcTemplate to query the database, so we say that JdbcTemplate is a very basic operation class.
Return getJdbcTemplate () .query (newPreparedStatementCreator (sqlToUse, params), rowMapper)
}
In the operation of Spring to JDBC, it is basically the encapsulation of API based on JDBC/Hibernate. These wrappers can be used directly, or can be configured in the IoC container for re-use, when used on the basis of the IoC container, you can see many transaction management-related processing parts, which are worth learning, where you can see the management of data sources-the management of session in Hibernate, the combination of threads, and so on.
For more information, please follow the Wechat official account: IT (it_)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.