[Spring Frame] Spring Jdbctmplate Basics Primer Summary.

Source: Internet
Author: User
Tags connection pooling

Objective:
The basic use of spring IOC and AOP is described earlier, and here's how spring JdbcTemplate is used.

One, overview
Here's a look at some of the templates that spring integrates:



As you can see, Spring provides a variety of supported persistence technologies, with simple-to-operate templates and callbacks.

Second, use JdbcTemplate

2.1 Spring JDBC is the persistence layer technology provided by spring
simplifies the development of the JDBC API, which is very similar to the dbutils framework of the Apache company

Specific development uses the JAR package structure:
|

2.2, Spring Configuring connection pooling
1, configure spring's built-in connection pool

1 <!--Configure Spring's built-in connection pool-->2 <bean id= "DataSource" class= " Org.springframework.jdbc.datasource.DriverManagerDataSource ">3     <property name=" Driverclassname "value= "Com.mysql.jdbc.Driver"/>4     <property name= "url" value= "jdbc:mysql:///spring_day02"/>5     < Property name= "username" value= "root"/>6     <property name= "password" value= "123"/>7 </bean>

2. Configuring the DBCP Connection pool

1 <!--Configure DBCP connection pool-->2 <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >3     < Property Name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/>4     <property name= "url" value= "Jdbc:mysql :///spring_day02 "/>5     <property name=" username "value=" root "/>6     <property name=" password "value = "123"/>7 </bean>

Note: If you use the DBCP connection pool, you also need to import the spring Consolidated DBCP two jar packages.


3. C3P0 Connection Pool

1 <!--Configure C3P0 connection pool-->2 <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" >3     < Property Name= "Driverclass" value= "Com.mysql.jdbc.Driver"/>4     <property name= "Jdbcurl" value= "Jdbc:mysql :///spring_day02 "/>5     <property name=" user "value=" root "/>6     <property name=" password "value=" 123 "/>7 </bean>

4, introduce the attribute file: write the Jdbc.properties file, then inject the configuration file directly into spring
Jdbc.properties configuration file:

Jdbc.driverclass=com.mysql.jdbc.driverjdbc.url=jdbc:mysql:///spring_day02jdbc.user=rootjdbc.password=123
  Introducing a property file in spring's core configuration: two ways
1 <!--Introduction: Introducing a Property file-->2 <bean class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">3     <property name=" Location " Value= "Classpath:jdbc.properties"/>4 </bean>5 <!--Introduction Method II: Introduce the context of the constraints-->6 <context: Property-placeholder location= "Classpath:jdbc.properties"/>

Third, develop the case and use the spring JdbcTemplate for CRUD operations.

Customer.java:

1 public class Customer {2     private integer CID, 3     private String CNAME, 4     private integer age, 5 public     I Nteger Getcid () {6         return CID; 7     } 8 public     void Setcid (Integer CID) {9         this.cid = cid;10     }11     PU Blic string Getcname () {         cname;13}14 public     void Setcname (string cname) {         This.cname = cname;16     }17 public     integer getage () {         return age;19     }20 public     void Setage (Integer age) {         this.age = age;22     }23 @Override24     public     String toString () {         return "Customer [cid=" + CID + ", cname=" + CNAME + ", age=" + age26                 + "]";     }28     29}

Customerdao.java:

 1/** 2 * Completes the crud operation on customer 3 * 4 */5 public class Customerdao extends Jdbcdaosupport {All public void save ( Customer customer) {this.getjdbctemplate (). Update ("INSERT into customer values (null,?,?)", Ustomer.getcname (), Customer.getage ()),}17 public void update (customer customer) {This.getjdbctem Plate (). Update (update customer Set cname =?, age =?)  WHERE cid =? ", Customer.getcname (), Customer.getage (), Customer.getcid ());}23 public void Delete (Integer cid) {this.getjdbctemplate () update ("Delete from customer where cid =?", CI                 d);}28 public Integer findcount () {int count = This.getjdbctemplate (). queryForInt (31          "SELECT COUNT (*) from Customer"), return count;33}34 public String Findnamebyid (Integer CID) {36         String cname = This.getjdbctemplate (). queryForObject (37        "Select CNAME from customer where cid =?", String.class, CID); return cname;39}40-Public Cu Stomer FindByID (Integer CID) {Customer customer = This.getjdbctemplate (). queryForObject (sel         ECT * FROM customer WHERE cid =? ", beanpropertyrowmapper<customer> New (Customer.class), CID); 45 return customer;46}47 list<customer> findAll () {list<customer> List = thi S.getjdbctemplate (). Query ("SELECT * from Customer", New Beanpropertyrowmapper<customer> (customer.c Lass)); return list;52}53}

Springdemo2.java Test class:

 1 @RunWith (Springjunit4classrunner.class) 2 @ContextConfiguration ("Classpath:applicationContext2.xml") 3 public     Class SpringDemo2 {4 5 @Resource (name= "Customerdao") 6 private Customerdao Customerdao; 7 8 @Test 9         public void Demo1 () {Ten customer customer = new Customer (); Customer.setcname ("The Horse"); 13 Customer.setage Customerdao.save (Customer),}17 @Test19 public void Demo 2 () {Customer customer = new Customer (), Customer.setcid (8), Customer.setcname ("Horse "Customer.setage"); Customerdao.update (customer),}28, @Test30 p ublic void Demo3 () {customerdao.delete (7),}33 @Test35 public void Demo4 () {$ int C Ount = Customerdao.findcount (), PNs System.out.println (count),}39 @Test41 public void Demo5 () { A String cname = customeRdao.findnamebyid (8); System.out.println (CNAME),}45 @Test47 public void Demo6 () {48 Customer customer = Customerdao.findbyid (8), SYSTEM.OUT.PRINTLN (Customer),}51 @Test53 Pub LIC void Demo7 () {list<customer> customers = Customerdao.findall (); tomers) {System.out.println (customer), 57}58}59}

Applicationcontext.xml configuration file:

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3 x Mlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context= "http://www.springframework.org/schema/ Context "5 xsi:schemalocation=" 6 Http://www.springframework.org/schema/beans Http://www.springframework.org/schema /beans/spring-beans.xsd 7 Http://www.springframework.org/schema/context http://www.springframework.org/schema/ Context/spring-context.xsd "> 8 9 <context:property-placeholder location=" Classpath:jdbc.properties "/ >11 <!--configuring C3P0 connection pool-->13 <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource ">14 <property name=" Driverclass "value=" ${jdbc.driverclass} "/>15 <property name=" JdbcUrl "Val Ue= "${jdbc.url}"/>16 <property name= "user" value= "${jdbc.user}"/>17 <property name= "Password" Value= "${jdbc.password}"/>18 </bean>19 <!--configuration dao-->22 <bean id= "Customerdao" class= "Cn.itcast.jdbc.demo2.CustomerDao" &G t;23 <property name= "DataSource" ref= "DataSource"/>24 </bean>25 </beans>


Well, a basic crud operation is done, here we can find the configuration file is particularly concise, we just injected Customerdao a datasource, Then in the Customerdao.java can be used this.getjdbctemplate () to get to the JdbcTemplate instance, this principle is because our Customerdao inherited Jdbcdaosupport, Here we will look at its source code:

First we use This.getjdbctemplate to obtain a JdbcTemplate instance:

1/**2  * Return the jdbctemplate for this dao,3  * pre-initialized with the DataSource or set explicitly.4  */5 Public final JdbcTemplate Getjdbctemplate () {6   return this.jdbctemplate;7}

Is it worthwhile to return this this.jdbctemplate? Look at the source code is the original when we setdatasource generated JdbcTemplate instances.

1/**2  * Set the JDBC DataSource to being used by this dao.3  */4 public final void Setdatasource (DataSource datasourc e) {5     if (this.jdbctemplate = = NULL | | DataSource! = this.jdbcTemplate.getDataSource ()) {6         this.jdbctemplate = cr Eatejdbctemplate (DataSource); 7         inittemplateconfig (); 8     }9}

[Spring Frame] Spring Jdbctmplate Basics Primer Summary.

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.