SpringBoot之旅第五篇-數據訪問

来源:https://www.cnblogs.com/yuanqinnan/archive/2019/04/23/10753979.html
-Advertisement-
Play Games

一、引言 大部分系統都離不開數據訪問,資料庫包括SQL和NOSQL,SQL是指關係型資料庫,常見的有SQL Server,Oracle,MySQL(開源),NOSQL是泛指非關係型資料庫,常見的有MongoDB,Redis。 用spring開發時我們常用的ORM框架有JDBC、Mybatis,Hib ...


一、引言

大部分系統都離不開數據訪問,資料庫包括SQL和NOSQL,SQL是指關係型資料庫,常見的有SQL Server,Oracle,MySQL(開源),NOSQL是泛指非關係型資料庫,常見的有MongoDB,Redis。

用spring開發時我們常用的ORM框架有JDBC、Mybatis,Hibernate,現在最常用的應該是Mybatis。

在Springboot中對於數據訪問層,無論是SQL還是NOSQL,都預設採用整合Spring Data的方式進行統一處理,Springboot會幫我們添加大量自動配置,屏蔽了很多設置。並引入各種xxxTemplate,xxxRepository來簡化我們對數據訪問層的操作。對我們來說只需要進行簡單的設置即可。這篇就來學習springboot整合JDBC,mybatis、JPA。

我們需要用什麼數據訪問,就引入相關的start進行開發。

二、JDBC

jdbc是我們最先學習的一個資料庫框架,SpringBoot也進行了相應整合.

2.1、 引入依賴

<!--JDBC -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql 驅動-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

2.2、數據源配置

我們可以做個測試:

@Autowired
private DataSource dataSource;

@Test
public void test() throws SQLException {
    System.out.println(dataSource.getClass());
    Connection connection = dataSource.getConnection();
    System.out.println(connection);
    connection.close();
}

輸出為:com.zaxxer.hikari.HikariDataSource

說明預設數據源是com.zaxxer.hikari.HikariDataSource,而在springboot 2.0之前為org.apache.tomcat.jdbc.pool.DataSource。我們也可以通過改變spring.datasource.type 屬性來更改我們想自定義的數據源。數據源的相關配置都在DataSourceProperties,我們可以參考這個類進行配置。

2.3、DataSourceInitializer

DataSourceInitializer這裡面有兩個方法runSchemaScripts()可以運行建表語句,runDataScripts()可以運行插入數據的sql語句。

預設使用schema-.sql創建建表語句,用data-.sql插入數據語句,當然我們也可以自己配置:

spring:
  datasource:
    schema:
     - classpath:department.sql

2.4、操作資料庫

由於spingboot已經幫我們自動配置了,那我們可以直接使用JdbcTemplate進行資料庫操作:

@Autowired
JdbcTemplate jdbcTemplate;

@Test
public void jdbcTest(){
    List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from user ");
    System.out.println(mapList.get(0));
}

結果:{id=1, username=王五, birthday=null, sex=2, address=null}

三、整合Druid數據源

上面講到我們有預設的數據源,但一般情況我們還是會使用阿裡提供的Druid數據源,因為Druid提供的功能更多,並且能夠監控統計,這個時候我們需要先引入pom依賴,然後將spring.datasource.type 修改:

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.16</version>
</dependency>

Druid的常用配置如下:

type: com.alibaba.druid.pool.DruidDataSource
#   數據源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#   配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用於防火牆
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

配置之後不會立刻生效,我們還需要編寫配置類:

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }
}

再次運行上面查詢數據源的方法,可以得到如下結果:

註:必須引入日誌依賴,否則會報錯

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>
</dependency>

我們在加上Druid的監控配置:

//配置Druid的監控
//1、配置一個管理後臺的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    Map<String,String> initParams = new HashMap<>();

    initParams.put("loginUsername","admin");
    initParams.put("loginPassword","123456");
    initParams.put("allow","");//預設就是允許所有訪問
    initParams.put("deny","192.168.15.21");

    bean.setInitParameters(initParams);
    return bean;
}


//2、配置一個web監控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    Map<String,String> initParams = new HashMap<>();
    initParams.put("exclusions","*.js,*.css,/druid/*");

    bean.setInitParameters(initParams);

    bean.setUrlPatterns(Arrays.asList("/*"));

    return  bean;
}

這樣我們可以直接通過後臺監控數據源訪問情況。

四、Mybatis

第一步也是引入依賴:

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>

也導入Druid數據源,並加入之前學習Mybatis時用到的實體,而後就可以進行測試,Mybatis的使用也有兩種方法,註解版和配置文件版,註解版用的很少,一般都是配置文件。

4.1、註解版

@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    int updateDept(Department department);
}

測試:

@Autowired
UserMapper userMapper;

@Autowired
DepartmentMapper departmentMapper;

@Test
public void mybatisTest(){
    Department deptById = departmentMapper.getDeptById(1);
    System.out.println(deptById);

}

結果:Department(id=1, departmentName=AA)

4.2、配置文件版

使用配置文件版方式也很簡單,也是先新增一個介面:

@Mapper
public interface UserMapper {
    User queryUserById(Integer id);
}

然後新增一個全局配置文件:SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

裡面暫時什麼配置都不需要,然後再引入相應的XXXMapper.xml文件,最後在配置文件中加上掃描文件配置即可

mybatis:
  config-location: classpath:mybatis/SqlMapConfig.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

UserMapper.xml內容:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yuanqinnan.mapper.UserMapper">
    <select id="queryUserById" parameterType="int" resultType="com.yuanqinnan.model.User">
    SELECT * FROM `user`where id=#{id}
   </select>

</mapper>

測試:

@Test
public void mybatisTest(){
    Department deptById = departmentMapper.getDeptById(1);
    System.out.println(deptById);
    User userById = userMapper.queryUserById(1);
    System.out.println(userById);
}

Mybatis的配置就是這麼簡單,基本不需要額外配置。

五、JPA

JDBC和Mybatis我們之前都學習過,SpringBoot只不過是幫我們整合配置,而JPA我們之前沒有接觸過,所以還是要先解釋下,瞭解JPA之前我們先瞭解Spring Data:

Spring Data 項目的目的是為了簡化構建基於Spring 框架應用的數據訪問技術,包括非關係資料庫、Map-Reduce 框架、雲數據服務等等;另外也包含對關係資料庫的訪問支持。

Spring Data 主要特點是:

SpringData為我們提供使用統一的API來對數據訪問層進行操作;這主要是Spring Data Commons項目來實現的。Spring Data Commons讓我們在使用關係型或者非關係型數據訪問技術時都基於Spring提供的統一標準,標準包含了CRUD(創建、獲取、更新、刪除)、查詢、排序和分頁的相關操作。

SpringData幫我們封裝了資料庫操作,我們只需要進程介面,就可以進行操作,SpringData有如下統一的介面

Repository<T, ID extends Serializable>:統一介面 RevisionRepository<T, ID extends Serializable, N extends Number & Comparable<N>>:基於樂觀鎖機制 CrudRepository<T, ID extends Serializable>:基本CRUD操作 PagingAndSortingRepository<T, ID extends Serializable>:基本CRUD及分頁

我們要使用JPA,就是繼承JpaRepository,我們只要按照它的命名規範去對命名介面,便可以實現資料庫操作功能,這樣說有些抽象,還是用一個例子來說明:

第一步:引入依賴

  <!-- springdata jpa依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

第二步:編寫表對應實體:

//使用JPA註解配置映射關係
@Entity //告訴JPA這是一個實體類(和數據表映射的類)
@Table(name = "order") //@Table來指定和哪個數據表對應;order;
@Data
public class Order {

    @Id //這是一個主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主鍵
    private Integer id;

    @Column(name = "user_Id")
    private Integer userId;
    //這是和數據表對應的一個列
    @Column(name="number",length = 32)
    private String number;
    // 訂單創建時間,省略預設列名就是屬性名
    private Date createtime;
    // 備註
    private String note;
}

第三步:編寫倉庫介面:

@Repository
public interface OrderRepository extends JpaRepository<Order, Integer> {
}

這個時候OrderRepository 已經有了很多實現好的方法,我們只要跟著調用即可

測試:

@Autowired
OrderRepository orderRepository;

@Test
public void jpaTest(){
    List<Order> all = orderRepository.findAll();
    System.out.println(all);

}

一個簡單的JPA實現完成,當然JPA的內容很多,這裡只是一個非常簡單的例子,要進一步的學習的話還是要去看官方文檔。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 上一次我們已經通過代碼,簡單的認識了工廠方法模式,具體的思路請移步到 "設計模式之工廠模式(二)" ,進行查看。這次,讓我們通過設計模式的思想,來好好認識下工廠方法模式。 創建者和產品 所有工廠模式都用來封裝對象的創建。工廠方法模式(Factory Method Pattern)通過讓子類決定該創建 ...
  • log4j log4j log4j.rootLogger=INFO, stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.app ...
  • 文章首發: "結構型模式:橋接模式" 七大結構型模式之二:橋接模式。 簡介 姓名 :橋接模式 英文名 :Bridge Pattern 價值觀 :解耦靠我 個人介紹 : Decouple an abstraction from its implementation so that the two ca ...
  • 前言: 這是一篇面向對象作業總結,作業內容是模擬電梯調度,一共有三個階段,具體要求不詳述,第一階段只要求先來先服務電梯,第二次支持捎帶,第三次則需要多部電梯協調,通過換乘來完成請求。本次作業在優化方面效果不佳。設計比較統一,設計原則檢查放在最後。 第5次作業 類圖如下: 說明: 具體的來說,M是主入 ...
  • 騰訊雲伺服器 點擊添加紀錄,紅色框框裡面填寫自己的公網IP即可。 阿裡雲上搭建php+mysql服務,並使用ftp將本地php文件及資料庫文件上傳到伺服器 先搭建php+MySQL環境 下載 "xampp" 。 XAMPP(Apache+MySQL+PHP+PERL)是一個功能強大的建站集成軟體包。 ...
  • @ "TOC" 1.變數 變數用於存儲要在電腦程式中引用和操作的信息。它們的唯一目的是在記憶體中標記和存儲數據。然後可以在整個程式中使用這些數據。變數存儲在記憶體中的值。這就意味著在創建變數時會在記憶體中開闢一個空間。 基於變數的數據類型,解釋器會分配指定記憶體,並決定什麼數據可以被存儲在記憶體中。因此,變 ...
  • NumPy: 1、NumPy 是一個功能強大的第三方庫(需要自己安裝),主要用於對多維數組執行計算; 它提供了大量的庫函數和操作,可以幫助程式員更輕鬆地進行數值計算 2、可以和另外兩個第三方庫 SciPy 和 Matplotlib 一起使用從而在一定程度上替換對 Matlab 的使用 3、主要應用: ...
  • R語言基礎學習——D02 20190423內容綱要: 1、前言 2、向量操作 (1)常規操作 (2)不定長向量計算 (3)序列 (4)向量的刪除與保留 3、列表詳解 (1)列表的索引 (2)列表得元素屬性 (3)更改列表元素 (4)刪除列表元素 (5)合併兩個列表 (6)將列表轉換為向量 4、推薦 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...