Spring JDBC 提供了多个实用的数据库访问工具,以简化 JDBC 的开发,其中使用最多就是 JdbcTemplate。JdbcTemplate 是 Spring JDBC 核心包(core)中的核心类,它可以通过配置文件、注解、Java 配置类等形式获取数据库的相关信息,实现了对 JDBC 开发过程中的驱动加载、连接的开启和关闭、SQL 语句的创建与执行、异常处理、事务处理、数据类型转换等操作的封装。我们只要对其传入SQL 语句和必要的参数即可轻松进行 JDBC 编程。
1. 引入jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
2. 创建配置文件(context.xml)
在 spring 配置文件配置数据库连接池,配置 JdbcTemplate 对象,注入 DataSource。配置时用的是引用外部配置文件,所以还需要引入外部的属性文件,同时创建对象时是基于注解的所以还要开启组件扫描。
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="jdbc" />
<!--引入外部的属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}" ></property>
<property name="username" value="${jdbc.username}" ></property>
<property name ="password" value="${jdbc.password}" ></property>
</bean>
<!--创建jdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
在以上配置中,我们共定义了两个 Bean,
- dataSource 为数据库连接池对象的 Bean。
- jdbcTemplate 则为 JdbcTemplate 的 Bean,它由一个名为 datasSource 的属性
在 dataSource 中,定义了 4 个连接数据库的属性,如下表所示。
| 属性名 | 说明 |
|---|---|
| driverClassName | 所使用的驱动名称,对应驱动 JAR 包中的 Driver 类 |
| url | 数据源所在地址 |
| username | 访问数据库的用户名 |
| password | 访问数据库的密码 |
3. 外部属性配置文件(jdbc.properties)
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/myTest?characterEncoding=utf8&useUnicode=true&useSSL=false jdbc.username=root jdbc.password=123456
4. 创建User实体
package jdbc.bean;
public class User {
private String userId;
private String userName;
private String password;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String userId, String userName, String password) {
this.userId = userId;
this.userName = userName;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
5. 创建Dao操作层
public interface UserDao {
//添加方法
void add(User user);
//修改方法
void updateUser(User user);
}
Dao实现
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add(User user) {
//创建sql语句
String sql=" INSERT INTO user (userId, userName, password) VALUES (?, ?, ?) ";
// 调用方法实行
int updat = jdbcTemplate.update(sql,user.getUserId(),user.getUserName(),user.getPassword());
// 返回成功的条数
System.out.println(updat);
}
@Override
public void updateUser(User user) {
}
}
6. 创建业务层
package jdbc.service;
import jdbc.bean.User;
public interface UserService {
//添加方法
void addUser(User user);
//修改方法
void updateUser(User user);
}
service实现层
@Service(value = "userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void addUser(User user) {
userDao.add(user);
}
@Override
public void updateUser(User user) {
}
}
7. 测试类
public class TestUser {
@Test
public void testJdbcTemplate() {
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
UserService userService = context.getBean("userService", UserService.class);
//添加
User user = new User("001","Keafmd","11");
userService.addUser(user);
}
}
8. 创建数据库
CREATE DATABASE IF NOT EXISTS myTest; use myTest; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `userId` int(4) unsigned NOT NULL AUTO_INCREMENT COMMENT '学号', `userName` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名', `password` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码', PRIMARY KEY (`userId`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';