中文

https://graphql.cn/

接下來將以一個完整的示例演示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開啟后,將會提供一個UI界面供我們快速查詢測試使用

做好以上配置后,接下來就是建立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 ;
}

Repository定義

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

}

Service定義

@Service
public 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 ;
}

}

以上是基本的數據庫操作,很容易理解。接下來就是定義GraphQL Schema

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
}

有關graphql相關語法請參考上面提到的網址。接下來是定義訪問接口

Controller接口

@Controller
public 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);
}

}

訪問測試

只需訪問統一的入口即可:

#該訪問路徑可以在配置文件中修改

http://localhost:8080/graphql

這里是訪問的完整的信息,我們可以在請求的query中設置需要訪問的字段,如下:

只訪問book信息

只訪問部分字段信息

你需要訪問那些字段,是完全由客戶端定義的。

完畢!!

文章轉自微信公眾號@Spring全家桶實戰案例源碼

上一篇:

.NetCore之WebApi接口裸奔有風險(Jwt)

下一篇:

通過 GraphQL API 進行存儲型 XSS 賬戶接管 (ATO)
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費