- 导入必要的maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
- 简单配置连接mysql的数据库配置文件
db.properties
jdbc.user=root
jdbc.password=zwf1233
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/springstudy3
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
- 创建
applicationContext.xml
配置文件,添加包扫描,导入db配置文件并配置c3p0数据源,最后添加Spring的JdbcTemplete。<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="com.fafa.spring.*"></context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<bean id="jdbcTemplete" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
- 创建mysql数据库中的相关表及数据:
DROP TABLE IF EXISTS `departments`;
CREATE TABLE `departments` (
`ID` tinyint(10) NOT NULL AUTO_INCREMENT,
`DEPT_NAME` varchar(20) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
insert into `departments`(`ID`,`DEPT_NAME`) values (1,'财务部'),(2,'开发部'),(3,'公关部');
DROP TABLE IF EXISTS `employees`;
CREATE TABLE `employees` (
`ID` tinyint(10) NOT NULL AUTO_INCREMENT,
`LAST_NAME` varchar(20) DEFAULT NULL,
`EMAIL` varchar(50) DEFAULT NULL,
`DEPT_ID` tinyint(10) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
insert into `employees`(`ID`,`LAST_NAME`,`EMAIL`,`DEPT_ID`) values (1,'Tom','tom@163.com',1),(2,'Jerry','hery@163.com',2),(3,'Mike','mike@sohu.com',3),(4,'Rose','rose@sina.com',3),(5,'fafa','fafa@qq.com',2);
- 创建
JDBCTest
类:public class JDBCTest {
private ApplicationContext ctx = null;
private JdbcTemplate jdbcTemplate;
{
ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplete");
}
@Test
public void testDataSource() throws SQLException {
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}
测试结果:com.mchange.v2.c3p0.impl.NewProxyConnection@1113fd74 [wrapping: com.mysql.jdbc.JDBC4Connection@3764d36e]
- 使用
jdbcTemplete
更新数据:
@Test
public void testUpdate() {
String sql = "UPDATE employees SET last_name=? where id=?";
jdbcTemplate.update(sql, "Jack", 5);
}
测试结果(前后结果对比):
- 执行批量更新
@Test
public void testBatchUpdate(){
String sql = "INSERT INTO employees(last_name,email,dept_id) VALUES(?,?,?)";
List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{"AA","aa@fafa.com",1});
batchArgs.add(new Object[]{"BB","bb@fafa.com",2});
batchArgs.add(new Object[]{"CC","cc@fafa.com",3});
batchArgs.add(new Object[]{"DD","dd@fafa.com",3});
batchArgs.add(new Object[]{"EE","ee@fafa.com",2});
jdbcTemplate.batchUpdate(sql, batchArgs);
}
执行结果:
- 查询结果为对象:
新建Employee
类public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer deptId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", deptId=" + deptId + "]";
}
}
测试方法:
@Test
public void testQueryForObject() {
String sql = "SELECT id, last_name, email, dept_id as \"department.id\" FROM employees WHERE id=?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 5);
System.out.println(employee);
}
查询结果:
Employee [id=5, lastName=Jack, email=fafa@qq.com, deptId=null]
- 查询实体类集合:
@Test
public void testQueryForList(){
String sql = "SELECT id, last_name, email FROM employees WHERE id>?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
List<Employee> employee = jdbcTemplate.query(sql, rowMapper, 5);
System.out.println(employee);
}
测试结果:[Employee [id=6, lastName=AA, email=aa@fafa.com, deptId=null], Employee [id=7, lastName=BB, email=bb@fafa.com, deptId=null], Employee [id=8, lastName=CC, email=cc@fafa.com, deptId=null], Employee [id=9, lastName=DD, email=dd@fafa.com, deptId=null], Employee [id=10, lastName=EE, email=ee@fafa.com, deptId=null]]
- 获取单列值或作统计:
@Test
public void testQueryForObject2(){
String sql = "SELECT count(id) FROM employees";
long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
测试结果:10
- 使用Dao获取数据,新建
EmployeeDao
类:@Repository
public class EmployeeDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Employee get(Integer id){
String sql = "SELECT id, last_name, email FROM employees WHERE id=?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 5);
return employee;
}
}
测试类:public class JDBCTest {
private ApplicationContext ctx = null;
private EmployeeDao employeeDao;
{
ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
employeeDao = ctx.getBean(EmployeeDao.class);
}
@Test
public void testEmployeeDao(){
System.out.println(employeeDao.get(1));
}
}
测试结果:
Employee [id=5, lastName=Jack, email=fafa@qq.com, deptId=null]