Java EE series of Spring4 Learning Notes (10)--spring support for JDBC __spring use Jdbcdaosuppo

Source: Internet
Author: User
Tags aop

I. Introduction of the Jdbcdaosupport class

In the previous section of the Project database operation implementation class Studentdaoimpl class in order to use the spring operations database you need to first define the JdbcTemplate class object, this section introduces the spring to the JDBC support Jdbcdaosupport class, First take a look at some of the things in this class:

* * Copyright 2002-2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You could not use this file, except in compliance with the License. * You may obtain a copy of the License in * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by a Pplicable or agreed to in writing, software * Distributed under the License be distributed on ' as is ' basis, * WI
 Thout warranties or CONDITIONS of any KIND, either express or implied.
 * The License for the specific language governing permissions and * limitations under the License.

* * Package org.springframework.jdbc.core.support;

Import java.sql.Connection;

Import Javax.sql.DataSource;
Import Org.springframework.dao.support.DaoSupport;
Import org.springframework.jdbc.CannotGetJdbcConnectionException;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.datasource.DataSourceUtils; Import Org.springframework.jdbc.support.SQLExceptiontranslator;
 /** * Convenient Super class for jdbc-based data Access objects. * * <p>requires a {@link javax.sql.DataSource} to be set, providing a * {@link Org.springframework.jdbc.core.JdbcT
 Emplate} based on it to * subclasses through the ' {@link #getJdbcTemplate ()} method. * * <p>this base class is mainly intended for jdbctemplate usage but can * also being used when working with a Connec
 tion directly or when using * {@code org.springframework.jdbc.object} operation objects. * @author Juergen Hoeller * @since 28.07.2003 * @see #setDataSource * @see #getJdbcTemplate * @see * Org.springframew Ork.jdbc.core.JdbcTemplate * * Public abstract class Jdbcdaosupport extends Daosupport {private JdbcTemplate Jdbctempla


	Te
	 /** * Set The JDBC DataSource to is used by this DAO. */public final void Setdatasource (DataSource DataSource) {if (this.jdbctemplate = = NULL | | DataSource!= this.jdbctem Plate.getdatasource ()) {this.jdbctemplate = CREATEJDBCTEmplate (DataSource);
		Inittemplateconfig ();
	 }/** * Create a jdbctemplate for the given DataSource.
	 * Only invoked if populating the DAO with a DataSource reference! * <p>can is overridden in subclasses to provide a JdbcTemplate instance * with different configuration, or a Custo
	 M JdbcTemplate subclass. * @param dataSource the JDBC dataSource to create a jdbctemplate for * @return The new JdbcTemplate instance * @see #s Etdatasource * * protected JdbcTemplate createjdbctemplate (DataSource DataSource) {return new JdbcTemplate (DataSource
	);
	 }/** * Return the JDBC DataSource used by this DAO. * * Public final DataSource Getdatasource () {return (this.jdbctemplate!= null? This.jdbcTemplate.getDataSource (): Nu
	ll);
	 }/** * Set the jdbctemplate for this DAO explicitly, * as a alternative to specifying a DataSource.
		* * Public final void Setjdbctemplate (JdbcTemplate jdbctemplate) {this.jdbctemplate = JdbcTemplate; Inittemplateconfig ();
	 }/** * Return the JdbcTemplate for this DAO, * pre-initialized with the DataSource or set explicitly.
	* * Public final JdbcTemplate getjdbctemplate () {return this.jdbctemplate;
 }

	
}

You can see the object in this class that defines the JdbcTemplate class, and there is a get and set method for the object, which also has the set method of the DataSource class.

We modify the Studentdaoimpl class so that this class inherits the Jdbcdaosupport class:

Package Com.test.dao.impl;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.util.ArrayList;

Import java.util.List;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.core.RowCallbackHandler;

Import Org.springframework.jdbc.core.support.JdbcDaoSupport;
Import Com.test.dao.StudentDao;

Import com.test.model.Student; public class Studentdaoimpl extends Jdbcdaosupport implements studentdao{@Override public int addstudent (Student Stud
		ENT) {String sql = INSERT INTO t_student values (null,?,?);
		Object []params = new Object[]{student.getname (), Student.getage ()};
		 
	Return This.getjdbctemplate (). Update (SQL,PARAMS); @Override public int updatestudent (Student Student) {String sql = ' Update t_student set name=?,age=?
		where id=? ";
		Object []params = new Object[]{student.getname (), Student.getage (), Student.getid ()};
	Return This.getjdbctemplate (). Update (SQL,PARAMS); @Override public int deletestudent (int id) {STRing sql = "Delete from t_student where id=?";
		Object []params = new Object[]{id};
	Return This.getjdbctemplate (). Update (SQL,PARAMS);
		@Override public list<student> findstudents () {String sql = ' select * from T_student ';
		Final list<student> studentlist = new arraylist<student> (); This.getjdbctemplate (). query (SQL, new RowCallbackHandler () {@Override public void Processrow (ResultSet rs) throws S
				qlexception {Student Student = new Student ();
				Student.setid (Rs.getint ("id"));
				Student.setname (rs.getstring ("name"));
				Student.setage (Rs.getint ("Age"));
			Studentlist.add (student);
		}
			
		});
	return studentlist;
 }

}

This removes the object of the previously defined JdbcTemplate class and calls the Get method to obtain the JdbcTemplate class object in the parent class Jdbcdaosupport class.

There is no need to define an object for the JdbcTemplate class, modify the spring configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "Http://www.springframework.org/schema/aop" xmlns: context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/s CHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/c  Ontext http://www.springframework.org/schema/context/spring-context.xsd "> <bean id=" DataSource " class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > <property name= "driverclassname" va Lue= "${jdbc.driverclassname}"/> <property name= "url" value= "${jdbc.url}"/> <property name= "use Rname "value=" ${jdbc.username} "/> &Lt;property name= "Password" value= "${jdbc.password}"/> </bean> <context:property-placeholder location= " Jdbc.properties "/> <bean id=" Studentdao "class=" Com.test.dao.impl.StudentDaoImpl "> <property name=" Data Source "ref=" DataSource "></property> </bean> <bean id=" Studentservice "class=" Com.test.service.impl.StudentServiceImpl "> <property name=" Studentdao "ref=" Studentdao "></property" > </bean> </beans>

This removes the instance that defines the JdbcTemplate class and injects the DataSource object value into the Studentdao instance.


Run each test method with the same effect as the previous section.


Second, the use of Namedparameterjdbctemplate class

or in the previous blog project based on the modification. Using the Spring operations database in the previous section, you use the JdbcTemplate class, where you write the SQL statement and then call the methods in the JdbcTemplate class. The SQL statement is written here in the following format:

String sql= "INSERT into t_student values (null,?,?)";
		Object []params=new object[]{student.getname (), Student.getage ()};
		Return Jdbctemplate.update (Sql,params);

The argument to pass in is a question mark. This means that the code is not readable.

Instead of using the JdbcTemplate class, we use the other class Namedparameterjdbctemplate class supported by spring for JDBC operations, and this class uses less than JdbcTemplate. However, it supports named parameter variables.

The code for intercepting part of this class is:

* * Copyright 2002-2014 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You could not use this file, except in compliance with the License. * You may obtain a copy of the License in * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by a Pplicable or agreed to in writing, software * Distributed under the License be distributed on ' as is ' basis, * WI
 Thout warranties or CONDITIONS of any KIND, either express or implied.
 * The License for the specific language governing permissions and * limitations under the License.

* * Package org.springframework.jdbc.core.namedparam;
Import Java.util.LinkedHashMap;
Import java.util.List;
Import Java.util.Map;

Import Javax.sql.DataSource;
Import org.springframework.dao.DataAccessException;
Import Org.springframework.dao.support.DataAccessUtils;
Import Org.springframework.jdbc.core.ColumnMapRowMapper;
Import org.springframework.jdbc.core.JdbcOperations; ImPort Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.core.PreparedStatementCallback;
Import Org.springframework.jdbc.core.PreparedStatementCreator;
Import Org.springframework.jdbc.core.PreparedStatementCreatorFactory;
Import Org.springframework.jdbc.core.ResultSetExtractor;
Import Org.springframework.jdbc.core.RowCallbackHandler;
Import Org.springframework.jdbc.core.RowMapper;
Import Org.springframework.jdbc.core.SingleColumnRowMapper;
Import Org.springframework.jdbc.core.SqlParameter;
Import Org.springframework.jdbc.core.SqlRowSetResultSetExtractor;
Import Org.springframework.jdbc.support.KeyHolder;
Import Org.springframework.jdbc.support.rowset.SqlRowSet;

Import Org.springframework.util.Assert;  /** * Template class with a basic set of JDBC operations, allowing the use * of named parameters rather than-traditional
 '? ' placeholders. * * <p>this class delegates to a wrapped {@link #getJdbcOperations () jdbctemplate} * Once the substitution from NA MEd parameters to JDBC style '? ' placeholders was * done in execution time.
 It also allows for expanding a {@link java.util.List} * of values to the appropriate number of placeholders. * * <p>the underlying {@link org.springframework.jdbc.core.JdbcTemplate} is * exposed to allow for convenient acce
 SS to the traditional * {@link org.springframework.jdbc.core.JdbcTemplate} methods. * * <p><b>note:an instance of this class is thread-safe once configured.</b> * * @author Thomas RISB ERG * @author Juergen Hoeller * @since 2.0 * @see namedparameterjdbcoperations * @see org.springframework.jdbc.core.Jd Bctemplate */public class Namedparameterjdbctemplate implements Namedparameterjdbcoperations {/** Default maximum num


	ber of entries for this template ' s SQL cache:256/public static final int default_cache_limit = 256;

	/** the JdbcTemplate we are wrapping * * Private final jdbcoperations classicjdbctemplate; private volatile int cachelimit = DefauLt_cache_limit;  /** Cache of original SQL String to parsedsql representation */@SuppressWarnings ("serial") private final map<string, parsedsql> Parsedsqlcache = new linkedhashmap<string, parsedsql> (Default_cache_limit, 0.75f, true) {@Ove Rride protected Boolean removeeldestentry (Map.entry<string, parsedsql> eldest) {return size () > Getcach
				Elimit ();


	}
			};
	 /** * Create A new namedparameterjdbctemplate for the given {@link DataSource}.
	 * <p>creates a classic Spring {@link org.springframework.jdbc.core.JdbcTemplate} and wraps it. * @param dataSource the JDBC dataSource to access */public namedparameterjdbctemplate (DataSource dataSource) {Asser
		T.notnull (DataSource, "DataSource must not to be null");
	This.classicjdbctemplate = new JdbcTemplate (DataSource); @Override public <T> t Query (String SQL, Sqlparametersource Paramsource, resultsetextractor<t> rse) t Hrows DataAccessException {return GETJDBCOPerations (). Query (Getpreparedstatementcreator (SQL, Paramsource), RSE); @Override Public <T> T query (String sql, map<string,?> Parammap, resultsetextractor<t> rse) thr
	OWS DataAccessException {return query (SQL, new Mapsqlparametersource (Parammap), RSE);  @Override Public <T> T query (String sql, resultsetextractor<t> rse) throws DataAccessException {return
	Query (SQL, emptysqlparametersource.instance, RSE); @Override public void query (String sql, Sqlparametersource Paramsource, RowCallbackHandler rch) throws Dataaccesse
	xception {getjdbcoperations (). Query (Getpreparedstatementcreator (SQL, Paramsource), RCH); @Override public void query (String sql, map<string,?> Parammap, RowCallbackHandler rch) throws Dataaccessex
	ception {query (SQL, new Mapsqlparametersource (Parammap), RCH); @Override public void query (String sql, RowCallbackHandler rch) throws DataAccessException {query SQL, Emptysqlpar Ametersource.
	INSTANCE, RCH); @Override public int update (String sql, Sqlparametersource Paramsource) throws DataAccessException {return getjdb
	Coperations (). Update (Getpreparedstatementcreator (SQL, Paramsource)); @Override public int update (String sql, map<string,?> parammap) throws DataAccessException {return update (s
	QL, New Mapsqlparametersource (Parammap)); @Override public int update (String sql, Sqlparametersource Paramsource, Keyholder generatedkeyholder) throws Dataa
	ccessexception {return update (SQL, Paramsource, generatedkeyholder, NULL);
 }

	
	
}

You can see that there are no attributes in this class that need to be assigned, but you need to pass in the object of the DataSource class when you construct the object of this class.


1. Modify the Studentdaoimpl Class code:

Package Com.test.dao.impl;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.util.ArrayList;

Import java.util.List;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.core.RowCallbackHandler;
Import Org.springframework.jdbc.core.namedparam.MapSqlParameterSource;

Import Org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
Import Com.test.dao.StudentDao;

Import com.test.model.Student;
	
	

	public class Studentdaoimpl implements studentdao{private Namedparameterjdbctemplate namedparameterjdbctemplate;
		public void Setnamedparameterjdbctemplate (Namedparameterjdbctemplate namedparameterjdbctemplate) {
	This.namedparameterjdbctemplate = namedparameterjdbctemplate;
		@Override public int addstudent (Student Student) {String sql= ' insert into t_student values (null,:name,:age) ";
		Mapsqlparametersource SPS = new Mapsqlparametersource ();
		Sps.addvalue ("Name", Student.getname ()); Sps.addvalue ("Age", Student.getage ());
	Return Namedparameterjdbctemplate.update (Sql,sps); @Override public int updatestudent (Student Student) {String sql= update t_student set name=:name,age=:age where ID
		=:id ";
		Mapsqlparametersource SPS = new Mapsqlparametersource ();
		Sps.addvalue ("Name", Student.getname ());
		Sps.addvalue ("Age", Student.getage ());
		Sps.addvalue ("id", Student.getid ());
	Return Namedparameterjdbctemplate.update (Sql,sps);
		@Override public int deletestudent (int id) {String sql= ' delete from t_student where Id=:id ';
		Mapsqlparametersource SPS = new Mapsqlparametersource ();
		Sps.addvalue ("id", id);
	Return Namedparameterjdbctemplate.update (Sql,sps);
		@Override public list<student> findstudents () {String sql= ' select * from T_student ';
		Final list<student> studentlist=new arraylist<student> (); Namedparameterjdbctemplate.query (SQL, new RowCallbackHandler () {@Override public void Processrow (ResultSet rs) thro WS SQLException {Student student=newStudent ();
				Student.setid (Rs.getint ("id"));
				Student.setname (rs.getstring ("name"));
				Student.setage (Rs.getint ("Age"));
			Studentlist.add (student);
		}
			
		});
	return studentlist;
 }

}

This class uses the namedparameterjdbctemplate. When writing an SQL statement, you need to pass in a parameter called ": Parameter name," which increases the readability of the program. The parameters passed in are saved in the object of the Mapsqlparametersource class using a key-value pair.


2. Modify the spring configuration file to:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "Http://www.springframework.org/schema/aop" xmlns: context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/s CHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/c Ontext http://www.springframework.org/schema/context/spring-context.xsd "> <bean id=" DataSource "cl ass= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > <property name= "driverclassname" value = "${jdbc.driverclassname}"/> <property name= "url" value= "${jdbc.url}"/> <property name= "Userna" Me "value=" ${jdbc.username} "/> <Property name= "Password" value= "${jdbc.password}"/> </bean> <context:property-placeholder location= Jdbc.properties "/> <bean id=" namedparameterjdbctemplate "class=" Org.springframework.jdbc.core.namedparam.Na
	
	
	Medparameterjdbctemplate "> <constructor-arg ref=" dataSource "></constructor-arg> </bean> <bean id= "Studentdao" class= "Com.test.dao.impl.StudentDaoImpl" > <property name= " Namedparameterjdbctemplate "ref=" namedparameterjdbctemplate "></property> </bean> <bean id=" Studentservice "class=" Com.test.service.impl.StudentServiceImpl "> <property name=" Studentdao "ref=" Studentdao "></property> </bean> </beans>

This defines an instance of the Namedparameterjdbctemplate class and uses the constructor method to inject the DataSource class object. Inject the defined Namedparameterjdbctemplate object instance into the Studentdaoimpl instance.


3. Run each test method, the effect is the same as using the JdbcTemplate class.


Related Article

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.