中文

https://graphql.cn/

接下來將以一個(gè)完整的示例演示GraphQL的使用。

環(huán)境配置

<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開啟后,將會(huì)提供一個(gè)UI界面供我們快速查詢測試使用

做好以上配置后,接下來就是建立2張表t_book和t_author。

實(shí)體定義

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

}

以上是基本的數(shù)據(jù)庫操作,很容易理解。接下來就是定義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
}

有關(guān)graphql相關(guān)語法請參考上面提到的網(wǎng)址。接下來是定義訪問接口

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

}

訪問測試

只需訪問統(tǒng)一的入口即可:

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

http://localhost:8080/graphql

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

只訪問book信息

只訪問部分字段信息

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

完畢!!

文章轉(zhuǎn)自微信公眾號(hào)@Spring全家桶實(shí)戰(zhàn)案例源碼

上一篇:

.NetCore之WebApi接口裸奔有風(fēng)險(xiǎn)(Jwt)

下一篇:

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

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場景實(shí)測,選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)