(二):使用 Spring Data JPA 實(shí)現(xiàn)數(shù)據(jù)讀取

前文:(一):搭建 Spring Boot 項(xiàng)目,并配置數(shù)據(jù)庫連接

接下來我們可以實(shí)現(xiàn)第一個(gè)讀取數(shù)據(jù)的服務(wù)了。

定義實(shí)體類 - POJO

Category 這個(gè)接口為例,要讀取CATEGORY表的數(shù)據(jù),那么首先要有一個(gè)實(shí)體類與該表做映射。實(shí)際上就是Java POJO類,每一個(gè)該類的對(duì)象,就代表數(shù)據(jù)庫表里的一行。

Category.java

@Entity
@Table(name = "CATEGORY")
public class Category implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  @Column(name = "CATEGORY_ID")
  private Integer categoryId;

  @Column(name = "CATEGORY_NM")
  private String categoryNm;

  @Column(name = "CREATE_ID")
  private String createId;

  @Column(name = "UPDATE_ID")
  private String updateId;

  @Column(name = "CREATE_TS")
  private Timestamp createTs;

  @Column(name = "UPDATE_TS")
  private Timestamp updateTs;
  
  // No-Arg Constructor
  // Getter and Setter
}

其中用到的一些Annotation:

@Entity - 標(biāo)注在類名上,且該類需要有一個(gè)無參構(gòu)造器和一個(gè)主鍵(實(shí)體類不可以是final的)參考:JPA規(guī)范-Entities
@Table - 指定該類對(duì)應(yīng)的數(shù)據(jù)庫表名,以及所在schema(若有的話)
@Id - 標(biāo)識(shí)該字段為主鍵
@Column - 標(biāo)識(shí)該字段對(duì)應(yīng)在數(shù)據(jù)庫表中某一個(gè)列的信息,如對(duì)應(yīng)的名稱 name = "CATEGORY_ID"

還有很多Annotation這里沒有用到,可以參考 Defining JPA Entities 有更詳細(xì)的說明。


獲取數(shù)據(jù) - Repository

在Spring Data中,Repository<T, ID>是一個(gè)空的"標(biāo)記"接口,它的子接口如CrudRepository<T, ID>JpaRepository<T, ID>都提供了一些基本的CRUD操作方法,我們只需要新建一個(gè)接口進(jìn)行繼承,并提供實(shí)體類ID類型,就可以使用那些方法。

這里我新建了一個(gè)CategoryRepository并繼承JpaRepository<T, ID>接口,類型參數(shù)分別是<Category, Integer>

CategoryRepository.java

public interface CategoryRepository extends JpaRepository<Category, Integer> {
}

這樣便可以使用諸如List<T> findAll();,這樣的基本方法。


業(yè)務(wù)邏輯 (實(shí)際干活層) - Service

在定義好對(duì)應(yīng)的Repository后,就可以在Service層注入CategoryRepository。調(diào)用時(shí)可以看到,有很多基本方法都可以調(diào)用,它們都來自于接口CrudRepositoryJpaRepository

CategoryService.java

@Service
public class CategoryService {
  @Autowired
  private CategoryRepository categoryRepository;

  public List<Category> getAll() {
    return categoryRepository.findAll();
  }
}

控制器 (對(duì)外接口層) - Controller

這層很簡(jiǎn)單,寫好要對(duì)外開放的接口即可,這里參考了RESTful接口的設(shè)計(jì)。

CategoryController.java

@RestController
@RequestMapping("/category")
public class CategoryController {
  @Autowired
  private CategoryService categoryService;

  @GetMapping
  public List<Category> getAll() {
    return categoryService.getAll();
  }
}

關(guān)于RESTful的設(shè)計(jì),可以參考 RESTful API 設(shè)計(jì)指南。簡(jiǎn)而言之的理解,我認(rèn)為就是使用HTTP動(dòng)詞,URL作為資源。比如GET /category,即獲取所有的category數(shù)據(jù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容