成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

聊聊 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框架數據抽象層的基礎??梢哉f,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-06 08:31:53

數據庫基準測試

2024-10-12 15:29:56

2023-01-26 00:18:53

云原生數據庫云資源

2022-09-23 07:44:48

時序數據庫物聯網

2024-05-08 08:14:18

數據庫IO備份

2022-09-21 07:30:12

數據庫勒索病毒企業

2023-10-11 08:09:53

事務隔離級別

2024-09-13 08:59:20

2022-02-07 08:27:00

數據庫組件功能

2023-09-05 08:38:33

數據庫高可用測試

2022-10-17 09:03:52

2012-09-25 09:19:26

Spring數據庫雙數據庫

2022-12-05 09:10:21

2022-09-20 07:30:47

數據庫安全掃描

2024-09-09 09:19:57

2023-07-04 08:06:40

數據庫容器公有云

2021-09-12 17:25:12

SQLite數據庫

2023-12-13 08:22:45

SQLite關系型數據庫

2022-11-08 08:11:52

PG數據庫防誤
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 91色站 | 日日夜夜精品 | 亚洲国产小视频 | 国内久久精品 | 午夜小电影 | 中文字幕乱码一区二区三区 | 81精品国产乱码久久久久久 | 一区二区三区四区在线 | 东方伊人免费在线观看 | 国产一区二区三区精品久久久 | 国产成人精品免费视频 | 欧美一区二区三区在线播放 | 国产激情 | 99re在线| 老牛嫩草一区二区三区av | 九色 在线 | 亚洲精品乱 | 国产一区免费 | 99爱国产 | 91在线一区二区 | 久久精品视频网站 | 国产成人精品综合 | 国产欧美日韩一区 | 久久成人精品视频 | 国产一级视频 | 国产精品一区二区三区四区 | 日韩在线播放第一页 | 天堂一区二区三区 | 国产精品久久久久久久免费大片 | 久久久久久亚洲精品 | 国产精品久久久久久久久久久久 | 中文字幕亚洲一区 | 久久久无码精品亚洲日韩按摩 | 亚洲h在线观看 | 断背山在线观看 | 91在线看视频 | 久久免费观看一级毛片 | 亚洲午夜小视频 | 欧美一级在线 | 国产精品一区视频 | 美女久久 |