1. 程式人生 > >微服務:Spring Boot第三篇——資料訪問Spring Data JPA

微服務:Spring Boot第三篇——資料訪問Spring Data JPA

這篇要從HelloWorld進一步,實現從資料庫中取資料,然後顯示在web頁面上的功能,資料庫採用H2,這是一種嵌入式的資料庫,無需安裝獨立的客戶端或者伺服器端。

Hibernate是一種使用物件關係對映(Object-Relational Mapping)實現資料訪問和操作的技術,它將模型層的類與資料庫的表進行對映,這樣在程式操縱物件同時也可以實現對底層資料庫的操作,而不需要再去編寫底層資料庫程式碼。JPA即Java Persistence API就是由Hibernate主導的,基於物件關係對映的標準規則,Spring Data JPA是Spring Data的一個子專案,提供了基於JPA的Repository來減少JPA作為資料訪問方案的程式碼量。

首先建立H2資料庫,之前我們在下載專案的時候已經選擇了有h2的依賴,接下來在application.property檔案中寫入一些資料庫的配置。

spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.datasource.platform=h2
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql
logging.level.root=INFO
logging.level.org.hibernate=INFO
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE
Spring Boot配置檔案的可選項多達幾百個,建議用到的時候再去查詢。上面的schema和data分別是存放在source目錄下的資料庫初始化和插入資料的檔案,裡面的內容如下。

drop table user if exists;
create table user (id bigint generated by default as identity, username varchar(40), name varchar(20), age int(3), balance decimal(10,2), primary key (id));
上面是schema.sql的內容,下面是data.sql檔案的內容。

insert into user (id, username, name, age, balance) values (1, 'account1', '張三', 20, 100.00);
insert into user (id, username, name, age, balance) values (2, 'account2', '李四', 28, 180.00);
insert into user (id, username, name, age, balance) values (3, 'account3', '王五', 32, 280.00);
接下來建立user對應的實體類,在com.movie.example_1下建立entity包用來存放對應資料庫的實體類,建立User類,內容如下。

package com.movie.example_1.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GeneratorType;

import java.math.BigDecimal;

@Entity
public class User {
	@Id
	@GeneratedValue
	private Long id;
	@Column
	private String username;
	@Column
	private String name;
	@Column
	private Integer age;
	@Column
	private BigDecimal balance;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName() {
		return username;
	}
	public void setUsername(String userName) {
		this.username = userName;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public BigDecimal getBalance() {
		return balance;
	}
	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}

	
}
上面的宣告@Entity表明這是一個實體類,@Id說明下面這個屬性是主鍵,@GeneratedValue說明主鍵的生成規則為預設(AUTO),通過@Entity宣告我們可以通過操作該物件類來直接改變底層資料庫。

接下來需要建立資料訪問層,使用Spring Data JPA建立資料訪問層只需要定義一個繼承JpaRepository的介面即可。在com.movie.example_1下建立repository包,然後建立UserRepository介面,程式碼如下。

package com.movie.example_1.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.movie.example_1.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}
繼承JpaRepository介面意味著我們預設已經有了增刪改查一系列基本操作,如果要進行比較複雜的資料庫操作還需要實現自己的方法,不過對這個簡單的程式來說裡面不需要寫任何程式碼。

然後需要建立控制層,在com.movie.example_1.controller下建立UserController類,程式碼如下。

package com.movie.example_1.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.movie.example_1.repository.*;
import com.movie.example_1.entity.*;

@RestController
public class UserController {
	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/{id}")
	public User findById(@PathVariable Long id) {
		User findOne = this.userRepository.findOne(id);
		return findOne;
	}
}
基本過程和上一篇的HelloWorld類似,不過這次使用到了Bean,所以用@Autowired進行了注入,在一個方法或變數上加上這個註解,等於告訴Spring接下來有一個Bean需要被注入。@GetMapping等價於@RequestMapping(method=RequestMethod.GET). @PathVariable註解表明需要從URI中取出一個變數,也就是id

接下來執行專案,除了Hello之外就有另外一個頁面了,輸入http://localhost:8080/1會看到如下圖結果,後面這個1就是id,也可以換成2和3