接下來我們可以實(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)用,它們都來自于接口CrudRepository或JpaRepository:

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ù)