Spring JDBC
传统的JDBC在操作数据库时,需要先打开数据库连接,执行SQL语句,然后封装结果,最后关闭数据库连接等资源。频繁的数据库操作会产生大量的重复代码,造成代码冗余,Spring的JDBC模块负责数据库资源管理和错误处理,大大简化了开发人员对数据库的操作,使开发人员可以从频繁的数据库操作中解脱出来,从而将更多的精力投入编写业务逻辑中。
JdbcTemplate
针对数据库操作,Spring框架提供了JdbcTemplate类,JdbcTemplate是一个模板类,Spring JDBC中的更高层次的抽象类均在JdbcTemplate模板类的基础上创建。
JdbcTemplate类提供了操作数据库的基本方法,包括添加、删除、查询和更新。在操作数据库时,JdbcTemplate类简化了传统JDBC中的复杂步骤,这可以让开发人员将更多精力投入到业务逻辑中。
JdbcTemplate类继承自抽象类JdbcAccessor,同时实现了JdbcTemplate接口。抽象类JdbcAccessor提供了一些访问数据库时使用的公共属性,具体如下:
- DataSource:DataSource主要功能是获取数据库连接。在具体的数据操作中,它还提供对数据库连接的缓冲池和分布式事务的支持。
- SQLExceptionTranslator:SQLExceptionTranslator是一个接口,它负责对SQLException异常进行转译工作。
Spring JDBC的配置
Spring JDBC中的4个包说明:
包名 | 说明 |
---|---|
core(核心包) | 包含了JDBC的核心功能,包括JdbcTemplate类、SimpleJdbcInsert类、SimpleJdbcCall类以及NamedParameterJdbcTemplate类。 |
dataSource(数据源包) | 包含访问数据源的实用工具类,它有多种数据源的实现,可以在Java EE容器外部测试JDBC代码。 |
object(对象包) | 以面向对象的方式访问数据库,它可以执行查询、修改和更新操作并将返回结果作为业务对象,并且在数据表的列和业务对象的属性之间映射查询结果。 |
support(支持包) | 包含了core和object包的支持类,如提供异常转换功能的SQLException类。 |
Spring对数据库的操作都封装在了core、dataSource、object和support这4个包中,想要使用Spring JDBC,就需要对这些包进行配置。在Spring中,JDBC的配置是在配置文件applicationContext.xml中完成的。
配置数据源:包括数据库驱动、连接数据库url、连接数据库用户名、连接数据库密码。
<bean id="dataSource" class=
"org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- 连接数据库url -->
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/><!-- 连接数据库用户名 -->
<property name="password" value="root"/><!-- 连接数据库密码 -->
</bean>
配置JDBC模板:必须使用默认数据源。
<bean id="JdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
配置注入类
<bean id="xxx" class="Xxx">
<property name="JdbcTemplate" ref="JdbcTemplate"/>
</bean>
dataSource配置的4个属性:
属性名 | 含义 |
---|---|
driverClassName | 所使用的驱动名称,对应驱动JAR包中的Driver类 |
url | 数据源地址 |
username | 访问数据库的用户名 |
password | 访问数据库的密码 |
dataSource属性值的设定要求
在dataSource的4个属性中,需要根据数据库类型或者系统配置设置相应的属性值。例如,如果数据库类型不同,需要更改驱动名称;如果数据库不在本地,则需要将地址中的localhost替换成相应的主机IP;默认情况下,数据库端口号可以省略,但如果修改过MySQL数据库的端口号,则需要加上修改后的端口号。此外,连接数据库的用户名和密码需要与数据库创建时设置的用户名和密码保持一致。
接下来,我们通过JDBCTemplate的实现数据库的增删改查操作
首先实现数据库的配置如下:
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/test?useUnicode=true&
characterEncoding=utf-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置jdbc模板 JdbcTemplate -->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置注入类 -->
<bean id="user" class="com.lq.entities.User">
<property name="JdbcTemplate" ref="JdbcTemplate"/>
</bean>
创建项目,目录如下:
在pom文件里添加maven依赖,我们特意引入了spring-jdbc和mysql-connector-java依赖,为了实现jdbc操作。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.1.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>6.1.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>6.1.16</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!-- jdbc包依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.7</version>
</dependency>
<!-- 事务管理依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.7</version>
</dependency>
<!-- 数据库驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
创建实体类Account
package com.lq.entities;
/**
* @Author: Luqing Teacher
* @CreateTime: 2025-02-27
* @Description: Account
* @Version: 1.0
*/
public class Account {
private int id;
private String username;
private Double balance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", balance=" + balance +
'}';
}
}
创建接口AccountDao
package com.lq.dao;
import com.lq.entities.Account;
import java.util.List;
/**
* @Author: lzq
* @CreateTime: 2025-02-27
* @Description: AccountDao
* @Version: 1.0
*/
public interface AccountDao {
public int addAccount(Account account);
public int updateAccount(Account account);
public int deleteAccount(int id);
public Account findAccountById(int id);
public List<Account> findAllAccount();
}
增删改查的接口实现:
package com.lq.dao.impl;
import com.lq.dao.AccountDao;
import com.lq.entities.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
/**
* @Author: Luqing Teacher
* @CreateTime: 2025-02-27
* @Description: 实现类
* @Version: 1.0
*/
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int addAccount(Account acc) {
String sql = "INSERT INTO account (username, balance) VALUES (?, ?)";
Object[] obj = new Object[]{
acc.getUsername(),
acc.getBalance()
};
int result = this.jdbcTemplate.update(sql, obj);
return result;
}
@Override
public int updateAccount(Account account) {
String sql = "update account set username=?,balance=? where id=?";
Object[] obj = new Object[]{
account.getUsername(),
account.getBalance(),
account.getId()
};
int result = jdbcTemplate.update(sql, obj);
return result;
}
@Override
public int deleteAccount(int id) {
String sql = "delete from account where id=?";
int result = jdbcTemplate.update(sql, id);
return result;
}
@Override
public Account findAccountById(int id) {
String sql = "select * from account where id=?";
//创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
//将id绑定到sql中,并且将查询结果封装到Account对象中
Account account = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
return account;
}
@Override
public List<Account> findAllAccount() {
String sql = "select * from account";
RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
List<Account> accounts = this.jdbcTemplate.query(sql, rowMapper);
return accounts;
}
}
本案例的Spring配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/springjdbc?useUnicode=true&
characterEncoding=utf-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置jdbc模板 JdbcTemplate -->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="accountDao" class="com.lq.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="JdbcTemplate"/>
</bean>
</beans>
接下来进行测试:
package com.lq.test;
import com.lq.dao.AccountDao;
import com.lq.entities.Account;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.annotation.Target;
import java.util.List;
/**
* @Author: Luqing Teacher
* @CreateTime: 2025-02-27
* @Description: jdbcTest
* @Version: 1.0
*/
public class JdbcTest {
@Test
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("JdbcTemplate");
jdbcTemplate.execute("" +
"create table account("+ "id int primary key auto_increment,"
+"username varchar(50),"
+"balance double)");
System.out.println("创建成功");
}
@Test
public void test2(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao accountDao = (AccountDao) app.getBean("accountDao");
Account account = new Account();
account.setUsername("肖炎");
account.setBalance(1000.0);
int res = accountDao.addAccount(account);
if(res>0){
System.out.println("成功添加了"+res+"条数据");
}else{
System.out.println("添加失败");
}
}
@Test
public void test3(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao accountDao = (AccountDao) app.getBean("accountDao");
Account account = new Account();
account.setId(1);
account.setUsername("小医仙");
account.setBalance(1500.0);
int res = accountDao.updateAccount(account);
if(res>0){
System.out.println("成功修改了"+res+"条数据");
}else{
System.out.println("修改失败");
}
}
@Test
public void test4(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao accountDao = (AccountDao) app.getBean("accountDao");
int res = accountDao.deleteAccount(1);
if(res>0){
System.out.println("成功删除了"+res+"条数据");
}else{
System.out.println("删除失败");
}
}
@Test
public void test5(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao accountDao = (AccountDao) app.getBean("accountDao");
Account account = accountDao.findAccountById(2);
System.out.println(account);
System.out.println("------------------------");
List<Account> allAccount = accountDao.findAllAccount();
for (Account account1 : allAccount) {
System.out.println(account1);
}
}
}
JdbcTemplate类中常用的查询方法
方法 | 说明 |
---|---|
List query(Stringsql,RowMapper rowMapper) | 执行String类型参数提供的SQL语句,并通过参数rowMapper返回一个List类型的结果。 |
List query(Stringsql, PreparedStatementSetter pss, RowMapper rowMapper) | 根据String类型参数提供的SQL语句创建PreparedStatement对象,通过参数rowMapper将结果返回到List中。 |
List query(Stringsql, Object[]args, RowMapper rowMapper) | 使用Object[]的值来设置SQL语句中的参数值,rowMapper是个回调方法,直接返回List类型的数据。 |
queryForObject(Stringsql, RowMapper rowMapper, Object…args) | 将args参数绑定到SQL语句中,并通过参数rowMapper返回一个Object类型的单行记录。 |
queryForList(Stringsql,Object[]args, class<T>elementType) | 该方法可以返回多行数据的结果,但必须返回列表,args参数是sql语句中的参数,elementType参数返回的是List数据类型。 |