JDBC framework of spring (12)

JDBC framework overview

When using an ordinary JDBC database, it will be troublesome to write unnecessary code to handle exceptions, open and close database connections, etc. However, the spring JDBC framework is responsible for all the low-level details, from opening the connection, preparing and executing SQL statements, handling exceptions, handling transactions, and finally closing the connection.

So when you get data from the database, all you do is define the connection parameters, specify the SQL statements to be executed, and complete the required work each iteration.

Spring JDBC provides several methods and corresponding different classes and interfaces in the database. I'll show you the classic and most popular ways to use the jdbctemplate class framework. This is the central framework class that manages all database communication and exception handling.

Jdbctemplate class

The jdbctemplate class executes SQL queries, update statements and stored procedure calls, executes the iteration result set and extracts the return parameter values. It also catches JDBC exceptions and converts them to org springframework. General classes defined in Dao package, more information, exception hierarchy.

The instance of the jdbctemplate class is thread safe. So you can configure a single instance of the jdbctemplate, and then safely inject the shared reference into multiple Daos.

When using the jdbctemplate class, the common practice is to configure the data source in your spring configuration file, then inject the shared data source bean dependency into the Dao class, and create the jdbctemplate in the setting function of the data source.

Demonstration examples are as follows:

(1) Create a MySQL database and import the script. The library name can be named arbitrarily. Here it is named test, and the SQL script is:

(2) Create entity

(3) Create Dao

(4) Create studentmapper

(5) Create studentjdbc template

(6) Write the corresponding beans xml

(7) Write mainapp Java and run

The operation results are as follows:

The data in the data sheet changes from none to yes:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>