"Spring Combat"--15 Spring JDBC template uses

Source: Internet
Author: User

The previous article through the use of the traditional JDBC operation, you can experience the use of cumbersome and complex, the set of words, is used 20% to do the real work, 80% to do the repetitive work.

So through this article, you can understand the following content:

1 How to configure a data source

2 How to use templates in spring

3 How to set up a unified base class for data sources

First look at how to configure the data source

We can configure the data source in 3 ways:

1 Jndi configuration Data source

I have no use in this practice, I feel that every time to modify the configuration of the web containers such as Tomcat, is very troublesome.

2 using the DBCP data source connection pool

In general, this is the way, for the connection pool implementation, there are many kinds, such as dbcp,c3p0 and so on.

Users can make their own configuration for connection pooling, which facilitates the tuning of the database side.

If you want to connect to a pool of data sources thank you for understanding, you can poke the link.

Relatively speaking, the most commonly used is DBCP and c3p0.

3 JDBC-based drive data sources

This is the most basic to manage the data source through the driver, but there is no concept of connection pooling.

There are two ways to achieve this:

Drivermanagerdatasource: This is generally the case, in which case each request will return a new connection.

Singleconnectiondatasource: This is a connection that is used every time.

  

In order to be simple and convenient, the third kind of direct use.

  

Templates in spring and the provided base classes

There are three types of templates available in spring:

1 JdbcTemplate

Provides the simplest data access features.

2 Namedparameterjdbctemplate

With this template, parameters can be passed into the method as a condition of the query.

3 Simplejdbctemplate (this is generally used)

Combined with some automatic boxing and other functions, after 3.0, the integration of namedparameterjdbctemplate.

  

To avoid injecting jdbctemplate beans into our DAO every time, spring implements three corresponding base classes for us, and our DAO implementation classes need to inherit these base classes, so we can use the template directly.

The corresponding differences are:jdbcdapsupport, Simplejdbcdaosupport, Namedparameterjdbcdaosupport

  

Finally, the use of the program is introduced

First look at the bean.xml of the configuration data source

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/BEANS/SPR Ing-beans-3.0.xsd Http://www.springframework.org/schema/context http://www . springframework.org/schema/context/spring-context-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/T X http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.sp RINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">                             <BeanID= "DataSource"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource">        < Propertyname= "Driverclassname"value= "Com.mysql.jdbc.Driver"/>        < Propertyname= "url"value= "Jdbc:mysql://localhost:3306/test"/>        < Propertyname= "username"value= "root"/>        < Propertyname= "Password"value= "123qwe"/>    </Bean>        <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.simple.SimpleJdbcTemplate">        <Constructor-argref= "DataSource"/>    </Bean>        <BeanID= "Newjdbcdao"class= "Com.spring.chap5.dao.NewJdbcImpl" >        < Propertyname= "JdbcTemplate"ref= "JdbcTemplate" />    </Bean></Beans>

Here, we configure the DataSource, as well as the jdbctemplate, and finally inject jdbctemplate into the DAO implementation class.

Next DAO's interface :

 Public Interface NEWJDBC {    publicvoid InsertPerson (String id,string name,int.  );     publicvoid  Findpersonbyid (String ID);}

  DAO's implementation class :

 Public classNewjdbcimplImplementsnewjdbc{Privatesimplejdbctemplate JdbcTemplate;  Public voidsetjdbctemplate (simplejdbctemplate jdbctemplate) { This. JdbcTemplate =JdbcTemplate; }         Public voidInsertPerson (String id,string name,intAge ) {Jdbctemplate.update ("INSERT into persons (Id,name,age) values (?,?,?)", Id,name,age); }         Public voidFindpersonbyid (String id) { person person= Jdbctemplate.queryforobject ("SELECT * from persons where id =?"),                 NewParameterizedsinglecolumnrowmapper<person>(){                     PublicPerson Maprow (ResultSet RS,intRowNum)throwssqlexception{Person P=NewPerson (); P.setid (Rs.getstring (1)); P.setname (Rs.getstring (2)); P.setage (Rs.getint (3)); returnp;        }}, id); System.out.println ("ID:" +person.getid () + "Name:" +person.getname () + "Age:" +person.getage ()); }}

Finally, the class used for the test

 Public class Test {    publicstaticvoid  main (string[] args) {        new Classpathxmlapplicationcontext ("Bean.xml");         = (NEWJDBC) ctx.getbean ("Newjdbcdao");        Newjdbc.insertperson ("003", "Xingoo3", +);        Newjdbc.findpersonbyid ("003");}    }

The above is the spring JDBC-based template used.

As you can see, the process of creating a connection and releasing it is omitted relative to the previous traditional JDBC operations database.

Just the real implementation of the operation to the developer, this is the template design pattern application-the separation template and the implementation of the developer.

"Spring Combat"--15 Spring JDBC template uses

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.