Spring provides good support for JDBC technology.
Reflected in:
1) Spring support for c3p connection pool is perfect;
2) Spring provides jdbctemplate to JDBC to simplify the JDBC operation;
1. Steps to use
1) Introduction of JAR file
Spring-jdbc-3.2.5.release.jar
Spring-tx-3.2.5.release.jar
C3P0 Connection Pool Package
Database driver Package
2) Container Create DataSource Object
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans. XSD "> <BeanID= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource"> < Propertyname= "Driverclass"value= "Com.mysql.jdbc.Driver"></ Property> < Propertyname= "Jdbcurl"value= "Jdbc:mysql:///student"/> < Propertyname= "User"value= "root"/> < Propertyname= "Password"value= "juaner767"/> < Propertyname= "Initialpoolsize"value= "3"/> < Propertyname= "Maxpoolsize"value= "6"/> < Propertyname= "Maxstatements"value= "+"/> < Propertyname= "Acquireincrement"value= "2"/> </Bean> <BeanID= "Userdao"class= "Com.juaner.spring.jdbc.UserDao"> < Propertyname= "DataSource"ref= "DataSource"/> </Bean></Beans>
3) Using Connection pool objects
Public classUserdao {//Inject Datasorce PrivateDataSource DataSource; Public voidSetdatasource (DataSource DataSource) { This. DataSource =DataSource; } Public voidSave () {String SQL= "INSERT into student values (4, ' John Doe ')"; Connection Conn=NULL; PreparedStatement stmt=NULL; Try{conn=datasource.getconnection (); stmt=conn.preparestatement (SQL); Stmt.executeupdate (); Stmt.close (); Conn.close (); } Catch(Exception e) {e.printstacktrace (); } }}
2. Using JdbcTemplate optimization
Public void Save () { = "INSERT into student (name) VALUES (' John Doe ')"; // using spring optimization New JdbcTemplate (dataSource); Jdbctemplate.update (SQL); }
Encapsulates an object
String SQL1 = "SELECT * FROM Student"; List<Student> query = Jdbctemplate.query (SQL1,NewRowmapper<student>() { //How to encapsulate a row of records@Override PublicStudent Maprow (ResultSet ResultSet,intIthrowsSQLException {Student Student=NewStudent (); Student.setid (Resultset.getint ("id")); Student.setname (Resultset.getstring ("Name")); returnstudent; } });
Container creation JdbcTemplate
<BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate"> <Constructor-argref= "DataSource"/> </Bean> <BeanID= "Userdao"class= "Com.juaner.spring.jdbc.UserDao"> < Propertyname= "JdbcTemplate"ref= "JdbcTemplate"/> </Bean>
Spring's support for JDBC