1. 依赖包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
2. web.xml中引入spring容器的配置文件applicationContext.xml
关于springMVC的配置文章可参考:https://my.oschina.net/u/3697586/blog/1589945
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/confg/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3. applicationContext.xml容器配置
1)配置数据源
<context:property-placeholder location="classpath:/confg/jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
jdbc.properties
#Mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
2)根据数据源准备好jdbcTemplate Bean
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"/>
3) 配置需要注入jdbcTemplate的包(包下所有)
<context:component-scan base-package="com.skyautobuild.dao"/>
4. 两层注解注入POJO中
(必须一层service加一层DAO,缺一不可,不能直接跳过service去直接调用DAO)
@service (service)
package com.skyautobuild.service;
import com.skyautobuild.dao.ProjectDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProjectService {
@Autowired
private ProjectDao projectDao;
public void addProject(){
projectDao.addProj();
}
}
@Repository (DAO)
package com.skyautobuild.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class ProjectDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void addProj(){
jdbcTemplate.update("insert into project(numb,text) values('001','test')");
}
}