聊聊 Spring 数据库开发

运维 数据库运维
Spring的JDBC模块负责数据库资源管理和错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑当中。
  • 1. Spring JDBC
  • Spring JDBC的配置
  • 2. Spring JdbcTemplate的常用方法
    • execute()
  • 总结

GitHub:https://github.com/nateshao/ssm/tree/master/104-spring-jdbc

1. Spring JDBC

Spring JDBC模块有什么作用?

Spring的JDBC模块负责数据库资源管理和错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑当中。

Spring JdbcTemplate的解析

针对数据库的操作,Spring框架提供了JdbcTemplate类,该类是Spring框架数据抽象层的基础。可以说,JdbcTemplate类是Spring JDBC的核心类。

JdbcTemplate类的继承结构具体如下图所示:

从JdbcTemplate的继承关系图可以看出,JdbcTemplate类的直接父类是JdbcAccessor,该类为子类提供了一些访问数据库时使用的公共属性。

DataSource:其主要功能是获取数据库连接,还可以引入对数据库连接的缓冲池和分布式事务的支持,它可以作为访问数据库资源的标准接口。

SQLExceptionTranslator:该接口负责对SQLException进行转译工作。通过必要的设置获取SQLExceptionTranslator中的方法,可以使JdbcTemplate在需要处理SQLException时,委托SQLExceptionTranslator的实现类来完成相关的转译工作。

而JdbcOperations接口定义了在JdbcTemplate类中可以使用的操作集合,包括添加、修改、查询和删除等操作。

Spring JDBC的配置

Spring JDBC模块主要由4个包组成,分别是core(核心包)、dataSource(数据源包)、object(对象包)和support(支持包)。

从上表可以看出,Spring对数据库的操作都封装在了这几个包中,而想要使用Spring JDBC,就需要对其进行配置。

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> 
  6.  <!-- 1配置数据源 --> 
  7.  <bean id="dataSource" class= 
  8.      "org.springframework.jdbc.datasource.DriverManagerDataSource"
  9.   <!--数据库驱动 --> 
  10.   <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
  11.   <!--连接数据库的url --> 
  12.   <property name="url" value="jdbc:mysql://localhost:3306/spring" /> 
  13.   <!--连接数据库的用户名 --> 
  14.   <property name="username" value="root" /> 
  15.   <!--连接数据库的密码 --> 
  16.   <property name="password" value="123456" /> 
  17.  </bean> 
  18.  <!-- 2配置JDBC模板 --> 
  19.  <bean id="jdbcTemplate"  
  20.      class="org.springframework.jdbc.core.JdbcTemplate"
  21.   <!-- 默认必须使用数据源 --> 
  22.   <property name="dataSource" ref="dataSource" /> 
  23.  </bean> 
  24.   
  25.  <!--定义id为accountDao的Bean--> 
  26.  <bean id="accountDao" class="com.nateshao.jdbc.AccountDaoImpl"
  27.   <!-- 将jdbcTemplate注入到accountDao实例中 --> 
  28.   <property name="jdbcTemplate" ref="jdbcTemplate" /> 
  29.  </bean> 
  30.   
  31. </beans> 

 

 

 

关于上述示例dataSource配置中的4个属性说明,如下表所示:

注意:上表中的属性值在实际配置时,需要根据数据库类型和设置进行相应配置。

2. Spring JdbcTemplate的常用方法

“在JdbcTemplate核心类中,提供了大量的更新和查询数据库的方法,我们就是使用的这些方法来操作数据库的。

execute( ):execute(String sql)方法可用于执行sql语句update():update())用于执行插入、更新和删除操作query():query()用于执行数据查询操作

execute()

使用execute(String sql)方法执行建表的案例实现步骤如下:

  • 在MySQL中创建一个名为spring的数据库;
  • 创建Web项目,导入相关maven包;
  • 创建Spring配置文件,配置数据源和JDBC模板;
  • 创建测试类,
  • 测试程序。

Spring.sql

  1. CREATE DATABASE  IF NOT EXISTS `spring` ; 
  2.  
  3. USE `spring`; 
  4.  
  5. /*Table structure for table `account` */ 
  6.  
  7. DROP TABLE IF EXISTS `account`; 
  8.  
  9. CREATE TABLE `account` ( 
  10.   `id` int(11) NOT NULL AUTO_INCREMENT, 
  11.   `username` varchar(50) DEFAULT NULL
  12.   `balance` double DEFAULT NULL
  13.   PRIMARY KEY (`id`) 
  14. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; 
  15.  
  16. /*Data for the table `account` */ 
  17.  
  18. insert  into `account`(`id`,`username`,`balance`) values (2,'shaotongjie',2222),(3,'1',2222),(4,'a',2022),(5,'b',2322); 

Account.java

  1. package com.nateshao.jdbc; 
  2.  
  3. /** 
  4.  * @date Created by 邵桐杰 on 2021/10/15 15:50 
  5.  * @微信公众号 程序员千羽 
  6.  * @个人网站 www.nateshao.cn 
  7.  * @博客 https://nateshao.gitee.io 
  8.  * @GitHub https://github.com/nateshao 
  9.  * @Gitee https://gitee.com/nateshao 
  10.  * Description: 
  11.  */ 
  12. @Data 
  13. public class Account { 
  14.     private Integer id;       // 账户id 
  15.     private String username; // 用户名 
  16.     private Double balance;  // 账户余额 

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.    xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> 
  6.    <!-- 1配置数据源 --> 
  7.    <bean id="dataSource" class= 
  8.      "org.springframework.jdbc.datasource.DriverManagerDataSource"
  9.       <!--数据库驱动 --> 
  10.       <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
  11.       <!--连接数据库的url --> 
  12.       <property name="url" value="jdbc:mysql://localhost:3306/spring?useSSL=false" /> 
  13.       <!--连接数据库的用户名 --> 
  14.       <property name="username" value="root" /> 
  15.       <!--连接数据库的密码 --> 
  16.       <property name="password" value="123456" /> 
  17.    </bean> 
  18.    <!-- 2配置JDBC模板 --> 
  19.    <bean id="jdbcTemplate"  
  20.          class="org.springframework.jdbc.core.JdbcTemplate"
  21.       <!-- 默认必须使用数据源 --> 
  22.       <property name="dataSource" ref="dataSource" /> 
  23.    </bean> 
  24.     
  25.    <!--定义id为accountDao的Bean--> 
  26.    <bean id="accountDao" class="com.nateshao.jdbc.AccountDaoImpl"
  27.       <!-- 将jdbcTemplate注入到accountDao实例中 --> 
  28.       <property name="jdbcTemplate" ref="jdbcTemplate" /> 
  29.    </bean> 
  30.     
  31. </beans> 

AccountDao.java

  1. package com.nateshao.jdbc; 
  2.  
  3. import java.util.List; 
  4.  
  5. /** 
  6.  * @date Created by 邵桐杰 on 2021/10/15 15:50 
  7.  * @微信公众号 程序员千羽 
  8.  * @个人网站 www.nateshao.cn 
  9.  * @博客 https://nateshao.gitee.io 
  10.  * @GitHub https://github.com/nateshao 
  11.  * @Gitee https://gitee.com/nateshao 
  12.  * Description: 
  13.  */ 
  14. public interface AccountDao { 
  15.     // 添加 
  16.     public int addAccount(Account account); 
  17.  
  18.     // 更新 
  19.     public int updateAccount(Account account); 
  20.  
  21.     // 删除 
  22.     public int deleteAccount(int id); 
  23.  
  24.     // 通过id查询 
  25.     public int queryAccountById(int id); 
  26.     // 查询所有账户 
  27.     public List<Account> findAllAccount(); 
  28.  
  29.     Account findAccountById(int i); 

AccountDaoImpl.java

  1. package com.nateshao.jdbc; 
  2.  
  3. import org.springframework.jdbc.core.BeanPropertyRowMapper; 
  4. import org.springframework.jdbc.core.JdbcTemplate; 
  5. import org.springframework.jdbc.core.RowMapper; 
  6. import java.util.List; 
  7.  
  8. /** 
  9.  * @date Created by 邵桐杰 on 2021/10/15 15:55 
  10.  * @微信公众号 程序员千羽 
  11.  * @个人网站 www.nateshao.cn 
  12.  * @博客 https://nateshao.gitee.io 
  13.  * @GitHub https://github.com/nateshao 
  14.  * @Gitee https://gitee.com/nateshao 
  15.  * Description: 
  16.  */ 
  17. public class AccountDaoImpl implements AccountDao { 
  18.     // 声明JdbcTemplate属性及其setter方法 
  19.     private JdbcTemplate jdbcTemplate; 
  20.  
  21.     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { 
  22.         this.jdbcTemplate = jdbcTemplate; 
  23.     } 
  24.  
  25.     /** 
  26.      * 添加账户 
  27.      * @param account 
  28.      * @return 
  29.      */ 
  30.     public int addAccount(Account account) { 
  31.         // 定义SQL 
  32.         String sql = "insert into account(username,balance) value(?,?)"
  33.         // 定义数组来存放SQL语句中的参数 
  34.         Object[] obj = new Object[]{ 
  35.                 account.getUsername(), 
  36.                 account.getBalance() 
  37.         }; 
  38.         // 执行添加操作,返回的是受SQL语句影响的记录条数 
  39.         int num = this.jdbcTemplate.update(sql, obj); 
  40.         return num; 
  41.     } 
  42.  
  43.     /** 
  44.      * 更新账户 
  45.      * @param account 
  46.      * @return 
  47.      */ 
  48.     public int updateAccount(Account account) { 
  49.         // 定义SQL 
  50.         String sql = "update account set username=?,balance=? where id = ?"
  51.         // 定义数组来存放SQL语句中的参数 
  52.         Object[] params = new Object[]{ 
  53.                 account.getUsername(), 
  54.                 account.getBalance(), 
  55.                 account.getId() 
  56.         }; 
  57.         // 执行添加操作,返回的是受SQL语句影响的记录条数 
  58.         int num = this.jdbcTemplate.update(sql, params); 
  59.         return num; 
  60.     } 
  61.  
  62.     /** 
  63.      * 删除账户 
  64.      * @param id 
  65.      * @return 
  66.      */ 
  67.     public int deleteAccount(int id) { 
  68.         // 定义SQL 
  69.         String sql = "delete  from account where id = ? "
  70.         // 执行添加操作,返回的是受SQL语句影响的记录条数 
  71.         int num = this.jdbcTemplate.update(sql, id); 
  72.         return num; 
  73.     } 
  74.  
  75.     @Override 
  76.     public int queryAccountById(int id) { 
  77.         return 0; 
  78.     } 
  79.  
  80.     /** 
  81.      * 通过id查询账户数据信息 
  82.      * @param id 
  83.      * @return 
  84.      */ 
  85.     public Account findAccountById(int id) { 
  86.         //定义SQL语句 
  87.         String sql = "select * from account where id = ?"
  88.         // 创建一个新的BeanPropertyRowMapper对象 
  89.         RowMapper<Account> rowMapper = 
  90.                 new BeanPropertyRowMapper<Account>(Account.class); 
  91.         // 将id绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录 
  92.         return this.jdbcTemplate.queryForObject(sql, rowMapper, id); 
  93.     } 
  94.  
  95.     /** 
  96.      * 查询所有账户信息 
  97.      * @return 
  98.      */ 
  99.     public List<Account> findAllAccount() { 
  100.         // 定义SQL语句 
  101.         String sql = "select * from account"
  102.         // 创建一个新的BeanPropertyRowMapper对象 
  103.         RowMapper<Account> rowMapper = 
  104.                 new BeanPropertyRowMapper<Account>(Account.class); 
  105.         // 执行静态的SQL查询,并通过RowMapper返回结果 
  106.         return this.jdbcTemplate.query(sql, rowMapper); 
  107.     } 
  108.  

测试类JdbcTemplateTest.java

  1. package com.nateshao.jdbc; 
  2.  
  3. import org.junit.jupiter.api.Test; 
  4. import org.springframework.context.ApplicationContext; 
  5. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  6. import org.springframework.jdbc.core.JdbcTemplate; 
  7. import java.util.List; 
  8.  
  9. /** 
  10.  * @date Created by 邵桐杰 on 2021/10/15 15:57 
  11.  * @微信公众号 程序员千羽 
  12.  * @个人网站 www.nateshao.cn 
  13.  * @博客 https://nateshao.gitee.io 
  14.  * @GitHub https://github.com/nateshao 
  15.  * @Gitee https://gitee.com/nateshao 
  16.  * Description: 
  17.  */ 
  18. public class JdbcTemplateTest { 
  19.     /** 
  20.      * 使用execute()方法建表 
  21.      */ 
  22. // public static void main(String[] args) { 
  23. //    // 加载配置文件 
  24. //    ApplicationContext applicationContext = 
  25. //       new ClassPathXmlApplicationContext("applicationContext.xml"); 
  26. //    // 获取JdbcTemplate实例 
  27. //    JdbcTemplate jdTemplate = 
  28. //          (JdbcTemplate) applicationContext.getBean("jdbcTemplate"); 
  29. //    // 使用execute()方法执行SQL语句,创建用户账户管理表account 
  30. //    jdTemplate.execute("create table account(" + 
  31. //                      "id int primary key auto_increment," + 
  32. //                      "username varchar(50)," + 
  33. //                      "balance double)"); 
  34. //    System.out.println("账户表account创建成功!"); 
  35. // } 
  36.     @Test 
  37.     public void mainTest() { 
  38.         // 加载配置文件 
  39.         ApplicationContext applicationContext = 
  40.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  41.         // 获取JdbcTemplate实例 
  42.         JdbcTemplate jdTemplate = 
  43.                 (JdbcTemplate) applicationContext.getBean("jdbcTemplate"); 
  44.         // 使用execute()方法执行SQL语句,创建用户账户管理表account 
  45.         jdTemplate.execute("create table account(" + 
  46.                 "id int primary key auto_increment," + 
  47.                 "username varchar(50)," + 
  48.                 "balance double)"); 
  49.         System.out.println("账户表account创建成功!"); 
  50.     } 
  51.  
  52.     @Test 
  53.     public void addAccountTest() { 
  54.         // 加载配置文件 
  55.         ApplicationContext applicationContext = 
  56.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  57.         // 获取AccountDao实例 
  58.         AccountDao accountDao = 
  59.                 (AccountDao) applicationContext.getBean("accountDao"); 
  60.         // 创建Account对象,并向Account对象中添加数据 
  61.         Account account = new Account(); 
  62.         account.setUsername("千羽"); 
  63.         account.setBalance(1000.00); 
  64.         // 执行addAccount()方法,并获取返回结果 
  65.         int num = accountDao.addAccount(account); 
  66.         if (num > 0) { 
  67.             System.out.println("成功插入了" + num + "条数据!"); 
  68.         } else { 
  69.             System.out.println("插入操作执行失败!"); 
  70.         } 
  71.     } 
  72.  
  73.     @Test 
  74.     public void updateAccountTest() { 
  75.         // 加载配置文件 
  76.         ApplicationContext applicationContext = 
  77.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  78.         // 获取AccountDao实例 
  79.         AccountDao accountDao = 
  80.                 (AccountDao) applicationContext.getBean("accountDao"); 
  81.         // 创建Account对象,并向Account对象中添加数据 
  82.         Account account = new Account(); 
  83.         account.setId(1); 
  84.         account.setUsername("tom"); 
  85.         account.setBalance(2000.00); 
  86.         // 执行updateAccount()方法,并获取返回结果 
  87.         int num = accountDao.updateAccount(account); 
  88.         if (num > 0) { 
  89.             System.out.println("成功修改了" + num + "条数据!"); 
  90.         } else { 
  91.             System.out.println("修改操作执行失败!"); 
  92.         } 
  93.     } 
  94.  
  95.     @Test 
  96.     public void deleteAccountTest() { 
  97.         // 加载配置文件 
  98.         ApplicationContext applicationContext = 
  99.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  100.         // 获取AccountDao实例 
  101.         AccountDao accountDao = 
  102.                 (AccountDao) applicationContext.getBean("accountDao"); 
  103.         // 执行deleteAccount()方法,并获取返回结果 
  104.         int num = accountDao.deleteAccount(1); 
  105.         if (num > 0) { 
  106.             System.out.println("成功删除了" + num + "条数据!"); 
  107.         } else { 
  108.             System.out.println("删除操作执行失败!"); 
  109.         } 
  110.     } 
  111.  
  112.     @Test 
  113.     public void findAccountByIdTest() { 
  114.         // 加载配置文件 
  115.         ApplicationContext applicationContext = 
  116.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  117.         // 获取AccountDao实例 
  118.         AccountDao accountDao = 
  119.                 (AccountDao) applicationContext.getBean("accountDao"); 
  120.         // 执行findAccountById()方法 
  121.         Account account = accountDao.findAccountById(1); 
  122.         System.out.println(account); 
  123.     } 
  124.  
  125.     @Test 
  126.     public void findAllAccountTest() { 
  127.         // 加载配置文件 
  128.         ApplicationContext applicationContext = 
  129.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  130.         // 获取AccountDao实例 
  131.         AccountDao accountDao = 
  132.                 (AccountDao) applicationContext.getBean("accountDao"); 
  133.         // 执行findAllAccount()方法,获取Account对象的集合 
  134.         List<Account> account = accountDao.findAllAccount(); 
  135.         // 循环输出集合中的对象 
  136.         for (Account act : account) { 
  137.             System.out.println(act); 
  138.         } 
  139.     } 

多学一招:使用JUnit单元测试

在进行接口开发完成后,一般是写个单元测试or采用PostMan去测试,或者前端项目对接,一起调试。

在开发过程中,需要有相应的测试工作。依据测试目的不同,可以将软件测试分为单元测试、集成测试、确认测试和系统测试等。其中单元测试在软件开发阶段是最底层的测试,它易于及时发现并解决问题。JUnit就是一个进行单元测试的开源框架,下面以上个示例,来学习单元测试框架JUnit4的使用。

update()

update()方法可以完成插入、更新和删除数据的操作。在JdbcTemplate类中,提供了一系列的update()方法,其常用方法下表所示:

 

query()

“JdbcTemplate类中还提供了大量的query()方法来处理各种对数据库表的查询操作。其中,常用的几个query()方法如下表所示:

总结

这篇文章主要是对Spring框架中,使用JDBC进行数据操作的知识进行了详细讲解。

首先讲解了Spring JDBC中的核心类以及如何在Spring中配置JDBC,

然后通过案例讲解了Spring JDBC核心类JdbcTemplate中常用方法的使用。

通过这篇文章的学习,能够学会如何使用Spring框架进行数据库开发,并能深切的体会到Spring框架的强大。

 

责任编辑:武晓燕 来源: 程序员千羽
相关推荐

2019-02-12 11:45:05

Java数据库开发

2023-01-26 00:18:53

云原生数据库云资源

2023-01-06 08:31:53

数据库基准测试

2022-09-23 07:44:48

时序数据库物联网

2023-10-11 08:09:53

事务隔离级别

2022-09-21 07:30:12

数据库勒索病毒企业

2012-09-25 09:19:26

Spring数据库双数据库

2022-02-07 08:27:00

数据库组件功能

2023-09-05 08:38:33

数据库高可用测试

2022-10-17 09:03:52

2022-09-20 07:30:47

数据库安全扫描

2023-07-04 08:06:40

数据库容器公有云

2021-09-12 17:25:12

SQLite数据库

2023-12-13 08:22:45

SQLite关系型数据库

2011-03-03 11:07:57

Spring数据库访问ORM

2022-12-05 09:10:21

2011-07-25 09:45:51

树状结构数据库存储

2022-08-26 17:48:34

数据库建表数据库

2011-08-02 16:16:08

iPhone开发 SQLite 数据库

2011-03-21 13:53:45

数据库开发书写规范
点赞
收藏

51CTO技术栈公众号