環(huán)境:Springboot3.0.9
GraphQL 既是一種用于 API 的查詢(xún)語(yǔ)言也是一個(gè)滿足你數(shù)據(jù)查詢(xún)的運(yùn)行時(shí)。GraphQL 對(duì)你的 API 中的數(shù)據(jù)提供了一套易于理解的完整描述,使得客戶(hù)端能夠準(zhǔn)確地獲得它需要的數(shù)據(jù),而且沒(méi)有任何冗余,也讓 API 更容易地隨著時(shí)間推移而演進(jìn),還能用于構(gòu)建強(qiáng)大的開(kāi)發(fā)者工具。
向你的 API 發(fā)出一個(gè) GraphQL 請(qǐng)求就能準(zhǔn)確獲得你想要的數(shù)據(jù),不多不少。GraphQL 查詢(xún)總是返回可預(yù)測(cè)的結(jié)果。使用 GraphQL 的應(yīng)用可以工作得又快又穩(wěn),因?yàn)榭刂茢?shù)據(jù)的是應(yīng)用,而不是服務(wù)器。
GraphQL 查詢(xún)不僅能夠獲得資源的屬性,還能沿著資源間引用進(jìn)一步查詢(xún)。典型的 REST API 請(qǐng)求多個(gè)資源時(shí)得載入多個(gè) URL,而 GraphQL 可以通過(guò)一次請(qǐng)求就獲取你應(yīng)用所需的所有數(shù)據(jù)。這樣一來(lái),即使是比較慢的移動(dòng)網(wǎng)絡(luò)連接下,使用 GraphQL 的應(yīng)用也能表現(xiàn)得足夠迅速。
GraphQL API 基于類(lèi)型和字段的方式進(jìn)行組織,而非入口端點(diǎn)。你可以通過(guò)一個(gè)單一入口端點(diǎn)得到你所有的數(shù)據(jù)能力。GraphQL 使用類(lèi)型來(lái)保證應(yīng)用只請(qǐng)求可能的數(shù)據(jù),還提供了清晰的輔助性錯(cuò)誤信息。應(yīng)用可以使用類(lèi)型,而避免編寫(xiě)手動(dòng)解析代碼。
有關(guān)GraphQL的語(yǔ)法相關(guān)知識(shí),請(qǐng)參考
https://graphql.org/中文
https://graphql.cn/
接下來(lái)將以一個(gè)完整的示例演示GraphQL的使用。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-graphql</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope></dependency>
spring: datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/testjpa?serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&useSSL=false username: root password: xxxxxx type: com.zaxxer.hikari.HikariDataSource hikari: minimumIdle: 10 maximumPoolSize: 200 autoCommit: true idleTimeout: 30000 poolName: MasterDatabookHikariCP maxLifetime: 1800000 connectionTimeout: 30000 connectionTestQuery: SELECT 1 ---spring: jpa: generateDdl: false hibernate: ddlAuto: update openInView: true show-sql: true---spring: graphql: path: /graphql graphiql: enabled: true path: /graphiql cors: allow-credentials: true allowed-headers: '*' allowed-methods: '*' schema: locations: - classpath*:graphql/**/ file-extensions: - .graphqls - .gqls printer: enabled: true
注意:這里的
spring.graphql.graphql.enabled=true開(kāi)啟后,將會(huì)提供一個(gè)UI界面供我們快速查詢(xún)測(cè)試使用
圖片
做好以上配置后,接下來(lái)就是建立2張表t_book和t_author。
Book
@Entity@Table(name = "t_book")public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id ; private String name ; private Integer pageCount ; @Transient private List<Author> author = new ArrayList<>();}
Author
@Entity@Table(name = "t_author")public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id ; private String firstName ; private String lastName ; // Book表的主鍵 private Long bid ;}
BookRepository
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {}
AuthorRepository
public interface AuthorRepository extends JpaRepository<Author, Long>, JpaSpecificationExecutor<Author> { List<Author> findByBid(Long bid) ; }
@Servicepublic class BookService { @Resource private BookRepository bookRepository ; @Resource private AuthorRepository authorRepository ; public Book queryBook(Long id) { Book book = bookRepository.findById(id).orElse(null) ; List<Author> authors = authorRepository.findByBid(id) ; book.setAuthor(authors) ; return book ; } }
以上是基本的數(shù)據(jù)庫(kù)操作,很容易理解。接下來(lái)就是定義GraphQL Schema
schema { query: BookQuery}type BookQuery { bookById(id: ID): Book}type Book { id: ID name: String pageCount: Int author: [Author]}type Author { id: ID firstName: String lastName: String}
有關(guān)graphql相關(guān)語(yǔ)法請(qǐng)參考上面提到的網(wǎng)址。接下來(lái)是定義訪問(wèn)接口
@Controllerpublic class BookController { @Resource private BookService bookService; @Resource private AuthorRepository authorRepository; @SchemaMapping(typeName = "BookQuery", field = "bookById") public Book bookById(@Argument Long id) { return bookService.queryBook(id); }}
只需訪問(wèn)統(tǒng)一的入口即可:
#該訪問(wèn)路徑可以在配置文件中修改
http://localhost:8080/graphql
圖片
這里是訪問(wèn)的完整的信息,我們可以在請(qǐng)求的query中設(shè)置需要訪問(wèn)的字段,如下:
圖片
只訪問(wèn)book信息
只訪問(wèn)部分字段信息
你需要訪問(wèn)那些字段,是完全由客戶(hù)端定義的。
本文鏈接:http://www.www897cc.com/showinfo-26-5198-0.htmlSpringboot整合GraphQL使你的API更易理解可讀性更強(qiáng)
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com