Spring JDBC Detailed
This article is intended to describe the use of the spring JDBC module. The spring JDBC module is one of the basic modules of the spring framework.
Chszs, reprint need to indicate. Blog home:Http://blog.csdn.net/chszs
I. Overview
In the spring JDBC module, all classes can be divided into four separate packages:
1) Core
The core package, which contains the core capabilities of JDBC. There are many important classes in this package, including: The JdbcTemplate class, the Simplejdbcinsert class, the Simplejdbccall class, and the Namedparameterjdbctemplate class.
2) DataSource
That is, a data source package that accesses a utility class for a data source. It has multiple implementations of data sources that can test the JDBC code outside the Java EE container.
3) Object
The object package, which accesses the database in an object-oriented manner. It allows you to execute the query and return the result as a business object. It can map query results between the columns of the data table and the properties of the business object.
4) Support
The support package, which is the support class for the core package and the object package. For example, the SqlException class that provides exception conversion functionality.
Second, the configuration
Let's take the MySQL database as an example to start a simple data source configuration:
@Configuration @componentscan ("COM.CH.MYALBUMJDBC") public class Springjdbcconfig { @Bean public DataSource Mysqldatasource () { Drivermanagerdatasource dataSource = new Drivermanagerdatasource (); Datasource.setdriverclassname ("Com.mysql.jdbc.Driver"); Datasource.seturl ("Jdbc:mysql://localhost:3306/springjdbc"); Datasource.setusername ("Guest_user"); Datasource.setpassword ("Guest_password"); return dataSource;} }
Alternatively, you can use an embedded database for development or testing, such as quickly configuring and creating an instance with the Hsql embedded database:
@Beanpublic DataSource DataSource () { return new Embeddeddatabasebuilder () . SetType ( Embeddeddatabasetype.hsql) . Addscript ("Classpath:jdbc/schema.sql") . Addscript ("classpath:jdbc/ Test-data.sql "). Build ();}
Finally, you can also use the XML configuration to achieve the effect of the previous annotation configuration:
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > < Property Name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql:/ /localhost:3306/springjdbc "/> <property name=" username "value=" guest_user "/> <property name=" Password "value=" Guest_password "/></bean>
third, the use of JdbcTemplate and run query
1, the basic query
The JDBC template is the main API in the Spring JDBC module, which provides common database access capabilities:
int result = Jdbctemplate.queryforobject ("Select COUNT (*) from EMPLOYEE", Integer.class);
The following is a simple insert function:
public int addemplyee (int. ID) { return jdbctemplate.update ( "INSERT into EMPLOYEE VALUES (?,?,?,?)", 5, "Bill", "Gates", "USA");
Note the standard syntax for supplying parameters--using "? Characters Below, let's look at alternative syntax.
2. Query and named parameters
To get support for named parameters, we need to use the other JDBC template--namedparameterjdbctemplate provided by spring JDBC.
This class encapsulates the jbdctemplate and provides the use of the "? To override the traditional syntax for the specified parameter. It uses the passed parameters to replace the placeholder "? "To perform a query that passes the arguments:
Sqlparametersource namedparameters = new Mapsqlparametersource (). AddValue ("id", 1); return Namedparameterjdbctemplate.queryforobject ("Select first_name from EMPLOYEE WHERE ID =: id", Namedparameters, String.class);
Note that we are using Mapsqlparametersource to provide a named parameter for the value.
The following is a simple example of using the properties of a bean class to determine named parameters:
Employee Employee = new Employee (); Employee.setfirstname ("James"); String select_by_id = "Select COUNT (*) from EMPLOYEE WHERE first_name =: FirstName"; Sqlparametersource namedparameters = new Beanpropertysqlparametersource (employee); return Namedparameterjdbctemplate.queryforobject (select_by_id, Namedparameters, Integer.class);
Notice how we used the implementation of Beanpropertysqlparametersource to replace the specified named parameter.
3. Mapping query results to Java objects
Another useful feature is to map query results to Java objects-by implementing the RowMapper interface.
For example, for each row of results returned by the query, spring uses the row map to populate the Java bean:
public class Employeerowmapper implements rowmapper<employee> { @Override public Employee Maprow ( ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee (); Employee.setid (Rs.getint ("ID")); Employee.setfirstname (rs.getstring ("first_name")); Employee.setlastname (rs.getstring ("last_name")); Employee.setaddress (rs.getstring ("ADDRESS")); return employee; }}
Now, we pass the row mapper to the query API and get a fully populated Java object:
String query = "SELECT * from EMPLOYEE WHERE ID =?"; List<employee> employees = jdbctemplate.queryforobject (query, new object[] {ID}, new Employeerowmapper ());
Iv. Abnormal Conversion
Spring provides its own out-of-the-box data exception layering--dataaccessexception as the root exception, which is responsible for converting all the original exceptions.
So developers don't have to deal with the underlying persistence exception, because the spring JDBC module already encapsulates the underlying exception in the DataAccessException class and its subclasses.
This allows the exception handling mechanism to be independent of the specific database currently in use.
In addition to the default Sqlerrorcodesqlexceptiontranslator class, developers can also provide their own sqlexceptiontranslator implementations.
The following is a simple example of a custom sqlexceptiontranslator implementation that customizes the error message when an integrity constraint error occurs:
public class Customsqlerrorcodetranslator extends Sqlerrorcodesqlexceptiontranslator { @Override protected DataAccessException customtranslate (string task, String sql, SQLException SQLException) { if ( Sqlexception.geterrorcode () = = -104) { return new duplicatekeyexception ( "Custom Exception Translator- Integrity constraint violation. ", sqlException); } return null;} }
To use a custom exception converter, we need to pass it to jdbctemplate--via the Callingsetexceptiontranslator () method:
Customsqlerrorcodetranslator customsqlerrorcodetranslator = new Customsqlerrorcodetranslator (); Jdbctemplate.setexceptiontranslator (Customsqlerrorcodetranslator);
v. Using the SIMPLEJDBC class for JDBC operations
The Simplejdbc class provides an easy way to configure and execute SQL statements. These classes use the metadata of the database to build a basic query. The Simplejdbcinsert class and the Simplejdbccall class provide an easier way to perform inserts and stored procedure calls.
1, Simplejdbcinsert class
Below, let's take a look at the minimum configuration for executing a simple INSERT statement, based on the configuration of the Simplejdbcinsert class that produces the INSERT statement.
All you need to provide is: Table name, column name, and value. Let's first create the Simplejdbcinsert:
Simplejdbcinsert Simplejdbcinsert = new Simplejdbcinsert (dataSource). Withtablename ("EMPLOYEE");
Now, let's provide the column name and value, and do the following:
public int Addemplyee (Employee emp) { map<string, object> parameters = new hashmap<string, object> ();
parameters.put ("ID", Emp.getid ()); Parameters.put ("First_Name", Emp.getfirstname ()); Parameters.put ("Last_Name", Emp.getlastname ()); Parameters.put ("ADDRESS", emp.getaddress ()); return Simplejdbcinsert.execute (parameters);}
In order for the database to generate a primary key, we can use the Executeandreturnkey () API, and we also need to configure the actual auto-generated columns:
Simplejdbcinsert Simplejdbcinsert = new Simplejdbcinsert (dataSource) . Withtablename ("EMPLOYEE") . Usinggeneratedkeycolumns ("ID"); Number id = simplejdbcinsert.executeandreturnkey (parameters); SYSTEM.OUT.PRINTLN ("Generated ID-" + id.longvalue ());
Finally, we can also use Beanpropertysqlparametersource and Mapsqlparametersource to pass data.
2. Call the stored procedure with Simplejdbccall
Let's look at how to execute a stored procedure--we use Simplejdbccall abstraction:
Simplejdbccall Simplejdbccall = new Simplejdbccall (dataSource) . Withprocedurename ("Read_employee");p ublic Employee getemployeeusingsimplejdbccall (int id) { sqlparametersource in = new Mapsqlparametersource (). AddValue (" IN_ID ", id); Map<string, object> out = Simplejdbccall.execute (in); Employee EMP = new Employee (); Emp.setfirstname (String) out.get ("first_name"); Emp.setlastname (String) out.get ("last_name"); return EMP;}
six, batch processing operations
Another simple use case--a combination of multiple operations for batch processing
1. Use JdbcTemplate to perform basic batch operations
Use the JdbcTemplate class to perform basic batch operations with the BatchUpdate () API:
It is interesting to note that BatchPreparedStatementSetter is implemented.
Public int[] Batchupdateusingjdbctemplate (list<employee> employees) { return jdbctemplate.batchupdate (" INSERT into EMPLOYEE VALUES (?,?,?,?) ', new BatchPreparedStatementSetter () { @Override public void Setvalu ES (preparedstatement ps, int i) throws SQLException { ps.setint (1, Employees.get (i). GetId ()); Ps.setstring (2, Employees.get (i). Getfirstname ()); Ps.setstring (3, Employees.get (i). Getlastname ()); Ps.setstring (4, Employees.get (i). GetAddress (); } @Override public int getbatchsize () { return;} } );
2. Use Namedparameterjdbctemplate to perform batch operations
For batch operations, you can also choose to use Namedparameterjdbctemplate's batchupdate () API to execute.
This API is simpler than the previous one-there is no need to implement any additional interfaces to set parameters because it has an internal setter of prepared statements to pass the preset parameter values.
The parameter values can be passed to the Sqlparametersource array through the BatchUpdate () method.
sqlparametersource[] Batch = Sqlparametersourceutils.createbatch (Employees.toarray ()); int[] UpdateCounts = Namedparameterjdbctemplate.batchupdate ( "INSERT into EMPLOYEE VALUES (: ID,: firstName,: LastName,: Address)", Batch); return updatecounts;
Vii. Conclusion
This article describes the JDBC abstraction in the spring framework, covering the various features and practical examples built into the spring JDBC module.
Spring JDBC Detailed