主頁 > 後端開發 > SpringBoot整合SpringDataJPA

SpringBoot整合SpringDataJPA

2020-12-19 17:23:41 後端開發

SpringBoot整合SpringDataJPA

1.JPA是什么

首先,我們說說JPA是什么?

JPA(java persistence api),它并不是一個框架,而是一組規范,我覺得對于任何一個開發人員來說,理解“規范”這個詞應該不在話下,其中,Hibernate就實作了這個規范,而且那是相當成功的(其實TopLink和OpenJPA也都實作了JPA規范,不過它們被Hinernate的光環籠罩了),所以呢,當我們說到JPA的時候,好多人首先想到的就是Hibernate,

2.SpringBootData JPA是什么

SpringData:其實SpringData就是Spring提供了一個操作資料的框架,而SpringData JPA只是SpringData框架下的一個基于JPA標準操作資料的模塊,
SpringData JPA:基于JPA的標準資料進行操作,簡化操作持久層的代碼,只需要撰寫介面就可以,

廢話不多說了,直接開始

3.環境/版本一覽:

  • 開發工具:Intellij IDEA 2020.2.3
  • springboot:2.3.7.RELEASE
  • jdk:1.8.0_211
  • maven: 3.6.3

4.工程結構:

5.開始搭建:

  • 創建資料庫

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `pwd` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
BEGIN;
INSERT INTO `sys_user` VALUES (1, 'test', '123');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;
  • 新建專案

  • pom.xml依賴配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.niu</groupId>
    <artifactId>datasource</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>datasource</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- alibaba的druid資料庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • 創建組態檔 application.yml
server:
  port: 8080

spring:
  datasource:
    name: main_db
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相關配置
    druid:
      #監控統計攔截的filters
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #基本屬性
      url: jdbc:mysql://127.0.0.1:3306/t_user_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
      username: root
      password: Abcdef@123456
      #配置初始化大小/最小/最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      #獲取連接等待超時時間
      max-wait: 60000
      #間隔多久進行一次檢測,檢測需要關閉的空閑連接
      time-between-eviction-runs-millis: 60000
      #一個連接在池中最小生存的時間
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      #打開PSCache,并指定每個連接上PSCache的大小,oracle設為true,mysql設為false,分庫分表較多推薦設定為false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  • 創建model 類多的話可以使用逆向工程創建
@Entity(name = "sys_user") //name值代表資料庫對應的表名,如不寫默認按照物體類的駝峰命名法單詞中間加_
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"}) //加這個注解是為了防止本專案把jpa物件直接轉json有空值報錯
public class SysUser {

    
    @Id
    @GeneratedValue
    private Integer id;
    /**
     *
     *   這里是映射資料表欄位與物體欄位 若資料庫表欄位為 user_name  這里需要寫成
     *   @Column(name = "user_name") 
     *   private String userName;
     *   如果一致可以不寫   
     */
    @Column(name = "name") 
    private String name;

    private String pwd;
        //get/set省略,記得加上

}
  • 創建Repository
/**
 *  
 * JpaRepository<SysUser,Integer> 引數1 要映射的物體類
 *                                引數2 物體類主鍵的資料型別
 *  每個dao層介面都要繼承這個類
 **/
@Repository
public interface SysUserRepository  extends JpaRepository<SysUser,Integer> {


}
  • 創建service
@Service
public class UserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    public SysUser getUser(Integer id){
        return  sysUserRepository.getOne(id);
    }


}
  • 創建controller 這里我們讓介面都回傳json 使用@RestController注解
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{userId}")
    public SysUser user(@PathVariable  Integer userId){
        return userService.getUser(userId);
    }
}
  • 創建主類
@SpringBootApplication
public class SpringbootJPAApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootJPAApplication.class, args);
    }

}

6.啟動測驗

查看下日志:

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.7.RELEASE)

2020-12-17 10:05:32.976 INFO 3434 --- [ main] c.n.springboot.SpringbootJPAApplication : Starting SpringbootJPAApplication on MacBook-Pro.local with PID 3434 (/Users/laoniu/IdeaProjects/datasource/target/classes started by laoniu in /Users/laoniu/IdeaProjects/datasource)
2020-12-17 10:05:32.979 INFO 3434 --- [ main] c.n.springboot.SpringbootJPAApplication : No active profile set, falling back to default profiles: default
2020-12-17 10:05:33.606 INFO 3434 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-12-17 10:05:33.668 INFO 3434 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 55ms. Found 1 JPA repository interfaces.
2020-12-17 10:05:34.014 INFO 3434 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-12-17 10:05:34.021 INFO 3434 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-17 10:05:34.021 INFO 3434 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2020-12-17 10:05:34.096 INFO 3434 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-12-17 10:05:34.096 INFO 3434 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1058 ms
2020-12-17 10:05:34.150 INFO 3434 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
Thu Dec 17 10:05:34 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2020-12-17 10:05:34.627 INFO 3434 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
2020-12-17 10:05:34.774 INFO 3434 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-12-17 10:05:34.807 INFO 3434 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.25.Final
2020-12-17 10:05:34.903 INFO 3434 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-17 10:05:34.981 INFO 3434 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
2020-12-17 10:05:35.360 INFO 3434 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-12-17 10:05:35.367 INFO 3434 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-12-17 10:05:35.580 WARN 3434 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-12-17 10:05:35.680 INFO 3434 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-17 10:05:35.878 INFO 3434 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-12-17 10:05:35.890 INFO 3434 --- [ main] c.n.springboot.SpringbootJPAApplication : Started SpringbootJPAApplication in 3.227 seconds (JVM running for 3.93)
2020-12-17 10:05:49.330 INFO 3434 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-12-17 10:05:49.331 INFO 3434 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-12-17 10:05:49.335 INFO 3434 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Hibernate: select sysuser0_.id as id1_0_0_, sysuser0_.name as name2_0_0_, sysuser0_.pwd as pwd3_0_0_ from sys_user sysuser0_ where sysuser0_.id=?

可以看到最后一行是SpringDataJPA為我們生成的查詢陳述句,我們并沒有寫sql,只是呼叫的SpringDataJPA自帶的方法,讓我們去看一下SpringDataJPA都為我們提供哪些可用的方法

7.Repository介面的使用

7.1SpringDataJPA提供的方法

按照SpringDataJPA規范可以讓我們只寫方法就可以進行操作資料庫,讓我們試一下

7.2撰寫Repository介面方法

//方法名稱必須要遵循駝峰式命名規則,findBy(關鍵字)+屬性名稱(首字母大寫)+查詢條件(首字母大寫)  
SysUser findByNameAndPwd(String name,String pwd);

這樣就能完成基本的查詢

洗掉用deleteBy開頭方法

如果方法不能滿足我的需求呢,我們還可以通過@Query注解手動寫sql

8.@Query基本使用

   /***
     *
     * ?1表示第一個引數,?2表示第二個引數
     * 這里的寫法是hql寫法
     * nativeQuery = false 代表使用hql ,默認不設定的話就是false 默認使用的hql
     * 要想使用 原生的sql  改為 true即可
     */
    @Query(value = "from SysUser where name = ?1 and pwd =?2",nativeQuery = false)
    SysUser findByNameAndPwdUseSQL(String name,String pwd);

到此,SpringBoot整合SpringDataJPA基本的使用結束,代碼已經推送至github,https://github.com/1603565290m/springboot-jpa

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/237257.html

標籤:java

上一篇:selenium定時爬取長截圖

下一篇:spring boot 2.2.7 集成redis 注解快取

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more