Spring Boot整合GraphQL

RPC选型入门测试系列文章

GraphQL是一种用于API开发的查询语言和运行时环境。它由Facebook开发并于2015年开源。GraphQL的主要目标是提供一种更高效、灵活和易于使用的方式来获取和操作数据。与传统的RESTful API相比,GraphQL允许客户端精确地指定需要的数据,并减少了不必要的网络传输和数据处理。

采用GraphQL,甚至不需要有任何的接口文档,在定义了Schema之后,服务端实现Schema,客户端可以查看Schema,然后构建出自己需要的查询请求来获得自己需要的数据。

1、数据类型

1.1、标量类型
  1. Int -32位整型数字;
  2. Float-双精度浮点型;
  3. String-UTF‐8 字符序列;
  4. Boolean-布尔型,true 或者 false;
  5. ID-标识类型,唯一标识符,注意此ID为字符,如果使用Mysql自增长id,也会自动转为对应的字符串;
1.2. 高级数据类型
  1. Object - 对象,用于描述层级或者树形数据结构。Object类型有一个类型名,以及类型包含的字段。
auto 复制代码
type Product {
    id: ID!
    info: String!
    price: Float
}
12345

在此示例中,声明了Product对象类型,定义了3 个字段:

id:非空 ID 类型。

info:非空字符串类型。

price:浮点型。

  1. Interface-接口,用于描述多个类型的通用字;与 Object一样。
auto 复制代码
interface Product {
    id: ID!
    info: String!
    price: Float
}
12345
  1. Union-联合类型,用于描述某个字段能够支持的所有返回类型以及具体请求真正的返回类型;
  2. Enum-枚举,用于表示可枚举数据结构的类型;
auto 复制代码
enum Status {
  Yes
  No
}
type Product {
    id: ID!
    info: String!
    price: Float
    stat: Status
}
12345678910
  1. Input-输入类型input本质上也是一个type类型,是作为Mutation接口的输入参数。换言之,想要定义一个修改接口(add,update,delete)的输入参数对象,就必须定义一个input输入类型。
auto 复制代码
input BookInput {
    isbn: ID!
    title: String!
    pages: Int
    authorIdCardNo: String
}
123456
  1. List -列表,任何用方括号 ([]) 括起来的类型都会成为 List 类型。
auto 复制代码
type Product {
    id: ID!
    info: String
    price: Float
    images: [String]
}
123456
  1. Non-Null-不能为 Null,类型后边加!表示非空类型。例如,String 是一个可为空的字符串,而String!是必需的字符串。

基本操作

  • Query(只读操作)
auto 复制代码
#schema.graphqls定义操作
type Query {
    allBooks: [Book]!
    bookByIsbn(isbn: ID): Book
}

# 接口查询语法
query{
  allBooks {
    title
    author {
      name
      age
    }
  }
}
12345678910111213141516
  • Mutation(可写操作)
auto 复制代码
#schema.graphqls定义操作
type Mutation {
    createBook(bookInput: BookInput): Book
    createAuthor(authorInput: AuthorInput): Author
}

# mutation{
#   createAuthor(authorInput:{ 
#     idCardNo: "341234567891234567",
#     name:"test1",
#     age:38
#   }
#   ){
#     name 
#     age
#   }
# }

2、Spring Boot整合GraphQL

GraphQL只是一种架构设计,具体的实现需要各个技术平台自己实现,目前主流的开发语言基本都已经有现成的类库可以使用,GraphQL Java就是Java平台的实现。

spring-graphql中定义的核心注解如下:

  • @GraphQlController:申明该类是GraphQL应用中的控制器
  • @QueryMapping:申明该类或方法使用GraphQL的query操作,等同于@SchemaMapping(typeName = "Query"),类似于@GetMapping
  • @Argument:申明该参数是GraphQL应用的入参
  • @MutationMapping:申明该类或方法使用GraphQL的mutation操作,等同于@SchemaMapping(typeName = "Mutation")
  • @SubscriptionMapping:申明该类或方法使用GraphQL的subscription操作,等同于@SchemaMapping(typeName = "Subscription")
  • @SchemaMapping:指定GraphQL操作类型的注解,类似@RequestMapping
2.1、项目目录

项目代码目录

2.3、GraphQL的schema.graphql

GraphQL对应的schema.graphql定义文件

auto 复制代码
schema {
    query: Query,
    mutation: Mutation,
}

type Query {
    getUserById(id:Int) : [User],
}

input UserInput {
    username : String,
    password : String,
    name : String,
}
type Mutation {
    createUser(userInput: UserInput): User,
    updateUser(id: Int!, userInput: UserInput): User,
    deleteUser(id: ID!): Int,

}
type User {
    id : ID!,
    username : String,
    password : String,
    name : String,
}
2.4、Java代码

pom.xml依赖包文件

xml 复制代码
	<dependencies>
		<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>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.23</version>
		</dependency>
		<dependency>
			<groupId>com.graphql-java</groupId>
			<artifactId>graphql-java-extended-scalars</artifactId>
			<version>19.1</version>
		</dependency>
	</dependencies>
</project>

对应的数据库实体类

java 复制代码
package com.example.graphql.dao;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String username;
    private String password;
    private String name;

    public User(String username, String password, String name) {
        this.username = username;
        this.password = password;
        this.name = name;
    }
}

GraphQL对应的输入类

auto 复制代码
package com.example.graphql.dao;
import lombok.Data;
import java.time.OffsetDateTime;
@Data
public class UserInput {
    private String username;
    private String password;
    private String name;
}

操作数据库

在Spring Data JPA中使用JpaRepository接口类完成对数据库的操作

增加、修改

JpaRepository中,当保存的实体类主键ID在数据库中存在时进行修改操作,不存在则进行保存。

java 复制代码
    @Autowired
    private UserInfoRepository userInfoRepository;

    public void addUserInfo() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId("jHfnKlsCvN");
        userInfo.setLoginName("登录名");
        userInfo.setPassword("123456");
        userInfo.setAge(18);
        // 保存或修改用户信息, 并返回用户实体类
        UserInfo save = userInfoRepository.save(userInfo);
    }
删除【根据实体类主键删除】
java 复制代码
    @Autowired
    private UserInfoRepository userInfoRepository;

    public void deleteUserInfo() {
        // 根据实体类主键删除
        userInfoRepository.deleteById("111");
    }
查询
查询单个信息【findBy】

JpaRepository中根据某一个字段或者某几个字段查询时,就使用findBy方法。

这里给个例子,假设,我想根据loginName查询用户信息,就可以用findByLoginName查询用户信息,如果有多个条件后面就继续拼接AndXXX

假设,我想查询loginName等于某值,并且password等于某值的,就可以使用findByLoginNameAndPassword

java 复制代码
public interface UserInfoRepository extends JpaRepository<UserInfo, String> {
	// 根据登录名查询用户信息
    UserInfo findByLoginName(String loginName);
    // 根据登录名和密码查询用户信息
    UserInfo findByLoginNameAndPassword(String loginName, String password);
}
查询多个信息【findAllBy】

JpaRepository中根据某一个字段或者某几个字段查询时,就使用findAllBy方法,而接口根据某个条件查询写法跟查询单个信息时一样。

这里给个例子,假设,我想查询loginName等于某值的所有用户信息时,就写做findAllByLoginName

java 复制代码
public interface UserInfoRepository extends JpaRepository<UserInfo, String> {
	// 查询所有登录名叫做XXX的用户
	List<UserInfo> findAllByLoginName(String loginName);
}
对应的数据库操作类

```java
package com.example.graphql.servise.Repository;

import com.example.graphql.dao.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Repository
//必须声明事务,不然删除报错
@Transactional
public interface UserRepository extends JpaRepository<User, Long> {
 
  List<User> findById(int id);
//  List<User> updateById(int id);
  int deleteById(int id);

}

对外服务接口类

在service层中实现查询和删除:

java 复制代码
package com.example.graphql.servise;

import com.example.graphql.dao.User;
import com.example.graphql.servise.Repository.UserRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

  @Resource
  private UserRepository userRepository ;
  
  public List<User> queryUser(int id) {
    List<User> user = userRepository.findById(id);
    return user;
  }
  public int deleteUser(int id) {
    int bool = userRepository.deleteById(id);
    return bool;
  }
}

在controller层中配置增删改查接口:

复制代码
package com.example.graphql.controller;

import com.example.graphql.dao.User;
import com.example.graphql.dao.UserInput;
import com.example.graphql.servise.Repository.UserRepository;
import com.example.graphql.servise.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {


    @Resource
    private UserService userService;
    @Resource
    private UserRepository userRepository ;

    @QueryMapping
    public List<User> getUserById(@Argument int id) {
        return userService.queryUser(id);
    }

    @MutationMapping
    public int deleteUser(@Argument int id) {
        return userService.deleteUser(id);
    }

    @MutationMapping
    public User createUser(@Argument UserInput userInput) {
        User user = new User();
        System.out.println(userRepository);
        System.out.println(user);
        BeanUtils.copyProperties(userInput,user);
        userRepository.save(user);
        return user;
    }

    @MutationMapping
    public User updateUser(@Argument int id,@Argument UserInput userInput) {
        System.out.println(userInput);
        User user = new User();
        user.setId(id);
        BeanUtils.copyProperties(userInput,user);
        System.out.println(user);
        userRepository.save(user);
        return user;
    }
}

3、运行效果

3.1、添加用户
3.2、查询用户
3.3、更新用户
3.4、删除用户

4、总结

使用Spring for GraphQL试用了GraphQL后,它实现按需取数据的功能。服务器开发人员和前端开发人员可以通过schema.graphqls定义文件,协定好接口和数据,省掉写接口文档的工作。

客户端可以通过一次请求获取多个数据资源,而不需要发起多个请求。相对于传统的RESTful API,GraphQL的实现和后端处理逻辑可能更加复杂。需要编写解析器、验证查询、处理复杂的字段解析和数据获取等。

相关推荐
程序员岳焱11 分钟前
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
后端·sql·mysql
龚思凯17 分钟前
Node.js 模块导入语法变革全解析
后端·node.js
天行健的回响20 分钟前
枚举在实际开发中的使用小Tips
后端
wuhunyu26 分钟前
基于 langchain4j 的简易 RAG
后端
techzhi26 分钟前
SeaweedFS S3 Spring Boot Starter
java·spring boot·后端
酷爱码30 分钟前
Spring Boot 整合 Apache Flink 的详细过程
spring boot·flink·apache
cacyiol_Z1 小时前
在SpringBoot中使用AWS SDK实现邮箱验证码服务
java·spring boot·spring
写bug写bug2 小时前
手把手教你使用JConsole
java·后端·程序员
苏三说技术2 小时前
给你1亿的Redis key,如何高效统计?
后端
JohnYan2 小时前
工作笔记- 记一次MySQL数据移植表空间错误排除
数据库·后端·mysql