iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
Software Development

Spring boot 從零到寫出ChatGPT系列 第 12

Spring boot 從零開始 (12) - Spring Data JPA讓資料庫處理變得更輕鬆 (下集)

  • 分享至 

  • xImage
  •  

昨天提到了Spring data JPA的好處跟 @Repository的宣告,今天我們就來幫大家整理一下JPA常用的語法吧!

findBy語法

以下我們都會用原生SQL搭配介紹

  • findAll : 代表查詢這張表全部的資料,用法如下 👇
    List<Book> findAll();
    // SQL : Select * from Book;
  • findBy : 代表會用某個條件查詢資料表,用法如下 👇
     Book findBookByBookId(Integer bookId);
    /* SQL : Select * from Book where bookId = ? */

JPA中的查詢關鍵字

  • And : 等同於 SQL 中的 and 關鍵字,用法如下 👇
      Book findBookByBooIdAndName(Integer bookId, String name);
    /* SQL : Select * from Book where bookId = ? and name = ? */
  • Or:等同於 SQL 中的 or 關鍵字,用法如下 👇
      Book findBookByBooIdOrName(Integer bookId, String name);
    /* SQL : Select * from Book where bookId = ? or name = ? */
  • Between:等同於 SQL 中的 between 關鍵字
  • IsNull:等同於 SQL 中的 "is null",用法如下 👇
      Book findBookByBooIdIsNull();
    /* SQL : Select * from Book where bookId is null/
  • IsNotNull:等同於 SQL 中的 "is not null"

  • Like:等同於 SQL中的 "like",用法如下 👇

      List<Book> findBookByNameLike(String name);
    /* SQL : Select * from Book where name like '%?%'/
  • In:等同於 SQL 中的 "in",用法如下 👇
      List<Book> findBookByBookIdIn(List<Integer> bookIds);
    /* SQL : Select * from Book where bookId in (?)/

Spring Data JPA 也可以下原生SQL

你也可使用原生的語法 @Query

@Query 裡面要第一個參數註明是 nativeQuery = true
接著後面就可以下SQL語法了 !!!!

    @Query(nativeQuery = true, value = "select * from book where book_id = :bookId")
    Book findBookByBookId(@Param("bookId") Integer bookId);

這樣有沒有發現Spring data JPA真的很方便呢 /images/emoticon/emoticon07.gif


上一篇
Spring boot 從零開始 (11) - Spring Data JPA讓資料庫處理變得更輕鬆 (上集)
系列文
Spring boot 從零到寫出ChatGPT12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言