JAVA框架 Spring JDBC模板

一:引入jar包:

1、数据驱动jar包:

 dbcp依赖的包:

spring的事务包和数据库包:

IOC包AOP包、log4j的包:

所有的jar包:

 编写测试类:

注入JdbcTemplate类,该类的父类有方法 setDatasource:

在直接配置文件依赖注入这个Datasource。

然后在配置文件中注入BasicDatabsource这个类。

 1  <bean class="org.apache.commons.dbcp.BasicDataSource" id="basicDataSource">
 2         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
 3         <property name="url"  value="jdbc:mysql://localhost:3306/day_spring" />
 4         <property name="username" value="root" />
 5         <property name="password" value="root" />
 6     </bean>
 7 
 8     <bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate" >
 9         <property name="dataSource" ref="basicDataSource" />
10     </bean>

 测试类代码:

 1 package jd.com.springjdtem;
 2 
 3 
 4 import org.apache.commons.dbcp.BasicDataSource;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import javax.annotation.Resource;
12 
13 
14 @RunWith(SpringJUnit4ClassRunner.class)
15 @ContextConfiguration("classpath:applicationContext.xml")
16 public class temptest {
17 
18     @Resource(name = "jdbcTemplate")
19     private JdbcTemplate jdbcTemplate;
20 
21 //    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
22 //        this.jdbcTemplate = jdbcTemplate;
23 //    }
24 
25     @Test
26     public void testtemp(){
27         jdbcTemplate.update("INSERT  INTO  t_account VALUEs (NULL ,?,?) ","tom",123);
28     }
29 
30 
31 }

 需要注意的是:不能再测试类使用set方法,将jdbctemplate注入。使用Resource 注入。否则报空指针的问题!!!!!!!!!!!

原文地址:https://www.cnblogs.com/evilliu/p/8891332.html