GraphQL(9):Spring Boot集成Graphql简单实例

news2025/2/25 4:02:44

1 安装插件

我这边使用的是IDEA,需要先按照Graphql插件,步骤如下:

(1)打开插件管理

在IDEA中,打开主菜单,选择 "File" -> "Settings" (或者使用快捷键 Ctrl + Alt + S 或 Cmd + ,),然后在弹出的对话框中选择 "Plugins"。

(2)搜索GraphQL插件

在插件管理器中,你会看到一个搜索框。在搜索框中输入 "GraphQL" 或者其他相关的关键词,然后按下回车键或者点击搜索图标。

(3)安装插件

(4)重启IDEA

安装完成以后重启IDEA

2 新建数据库

脚本如下:


CREATE DATABASE IF NOT EXISTS `BOOK_API_DATA`;
USE `BOOK_API_DATA`;

CREATE TABLE IF NOT EXISTS `Book` (
    `id` int(20) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) DEFAULT NULL,
    `pageCount` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `Index_name` (`name`)
    ) ENGINE=InnoDB AUTO_INCREMENT=235 DEFAULT CHARSET=utf8;

CREATE TABLE `Author` (
     `id` INT(20) NOT NULL AUTO_INCREMENT,
     `firstName` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
     `lastName` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
     `bookId` INT(20) NULL DEFAULT NULL,
     PRIMARY KEY (`id`) USING BTREE,
     UNIQUE INDEX `Index_name` (`firstName`) USING BTREE,
     INDEX `FK_Author_Book` (`bookId`) USING BTREE,
     CONSTRAINT `FK_Author_Book` FOREIGN KEY (`bookId`) REFERENCES `BOOK_API_DATA`.`Book` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
    COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6
;



INSERT INTO `Book` (`id`, `name`, `pageCount`) VALUES (1, 'the golden ticket', '255');
INSERT INTO `Book` (`id`, `name`, `pageCount`) VALUES (2, 'coding game', '300');

INSERT INTO `Author` (`id`, `firstName`, `LastName`, `bookId`) VALUES (4, 'Brendon', 'Bouchard', 1);
INSERT INTO `Author` (`id`, `firstName`, `LastName`, `bookId`) VALUES (5, 'John', 'Doe', 2);

3 代码实现

下面实现一个简单的查询

3.1 引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
            <version>3.3.0</version>
        </dependency>

完整pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springbootgraphql</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath />
    </parent>

    <properties>
        <java.version>1.8</java.version>
<!--        <kotlin.version>1.1.16</kotlin.version>-->
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>26.0-jre</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3.2 新建实体类

新建Author实体类

package com.example.demo.model;

import javax.persistence.*;

@Entity
@Table(name = "Author", schema = "BOOK_API_DATA")
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Integer id;
    @Column(name = "firstname")
    String firstName;
    @Column(name = "lastname")
    String lastName;
    @Column(name = "bookid")
    Integer bookId;

    public Author(Integer id, String firstName, String lastName, Integer bookId) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.bookId = bookId;
    }

    public Author() {

    }

    public Integer getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }
}

新建Book实体类

package com.example.demo.model;

import javax.persistence.*;

@Entity
@Table(name = "Book", schema = "BOOK_API_DATA")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    @Column(name = "pagecount")
    private String pageCount;

    public Book(Integer id, String name, String pageCount) {
        this.id = id;
        this.name = name;
        this.pageCount = pageCount;
    }

    public Book() {

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPageCount() {
        return pageCount;
    }

    public void setPageCount(String pageCount) {
        this.pageCount = pageCount;
    }
}

新建输入AuthorInput实体

package com.example.demo.model.Input;


public class AuthorInput {

    String firstName;

    String lastName;

    Integer bookId;


    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }


    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }
}

3.3 新建repository类

新建AuthorRepository类

package com.example.demo.repository;

import com.example.demo.model.Author;
import org.springframework.data.repository.CrudRepository;

public interface AuthorRepository extends CrudRepository<Author, Integer> {
    Author findAuthorByBookId(Integer bookId);
}

新建BookRepository类

package com.example.demo.repository;

import com.example.demo.model.Book;
import org.springframework.data.repository.CrudRepository;

public interface BookRepository extends CrudRepository<Book, Integer> {

    Book findBookByName(String name);
}

3.4 新建Service层

package com.example.demo.service;

import com.example.demo.model.Author;
import com.example.demo.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AuthorSevice {
    @Autowired
    private AuthorRepository authorRepository;

    public void addAuthon(Author author) {
        authorRepository.save(author);
    }

    public Author queryAuthorByBookId(int bookid) {
        Author author = authorRepository.findAuthorByBookId(bookid);
        return author;
    }

}

3.5 新建控制器

package com.example.demo.controller;

import com.example.demo.model.Author;
import com.example.demo.model.Input.AuthorInput;
import com.example.demo.service.AuthorSevice;
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.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
public class AuthorController {
    @Autowired
    private AuthorSevice authorSevice;


    /**
     * 经典 hollo graphql
     */
    @QueryMapping
    public String hello(){
        return "hello graphql";
    }
    @QueryMapping
    public Author getAuthorBybookId(@Argument int bookid) {
        System.out.println("bookid:"+bookid);
        return authorSevice.queryAuthorByBookId(bookid);
    }


    @MutationMapping
    public Author createUser(@Argument AuthorInput authorInput) {
        Author author = new Author();
        BeanUtils.copyProperties(authorInput,author);
        authorSevice.addAuthon(author);
        return author;
    }
}

3.6 新建graphql文件

在resource文件中新建graphql文件

编写root.graphql文件

schema {
    query: Query
    mutation: Mutation
}
type Mutation{
}
type Query{
}

编写books.graphql文件

extend type Query {
    hello:String
    getAuthorBybookId(bookid:Int): Author
}

extend type Mutation {
    createUser(authorInput: AuthorInput):Author
}

input AuthorInput {
    firstName: String
    lastName: String
    bookId: Int
}


type Author {
    id: Int
    firstName: String
    lastName: String
    bookId: Int
}

type Book {
    id: Int
    name: String
    pageCount: String
    author: Author
}

3.7 编写yml配置文件

spring:
  jpa:
    hibernate:
      use-new-id-generator-mappings: false
  graphql:
    graphiql:
      enabled: true
    websocket:
      path: /graphql
    schema:
      printer:
        enabled: true
      locations: classpath:/graphql   #test.graphql文件位置
      file-extensions: .graphql
  datasource:
    url: jdbc:mysql://192.168.222.156:3306/book_api_data?useUnicode=true&characterEncoding=utf-8&useSSL=false
    password: 123456
    username: root
server:
  port: 8088

3.8 编写启动类

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class graphqlApplication {
    public static void main(String[] args) {
        SpringApplication.run(graphqlApplication.class,args);
    }
}

4 启动测试

启动后访问http://localhost:8088/graphiql?path=/graphql&wsPath=/graphql

 测试查询功能

测试新增功能

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1824091.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【测试】软件测试方案—实际项目直接套用(Word原件)

1. 引言 1.1. 编写目的 1.2. 项目背景 1.3. 读者对象 1.4. 参考资料 1.5. 术语与缩略语 2. 测试策略 2.1. 测试完成标准 2.2. 测试类型 2.2.1. 功能测试 2.2.2. 性能测试 2.2.3. 安全性与访问控制测试 2.3. 测试工具 3. 测试技术 4. 测试资源 4.1. 人员安排 4.2. 测试环境 4.2.…

宝藏速成秘籍(5)插入排序法

一、前言 1.1、概念 插入排序&#xff08;Insertion Sort&#xff09;是一种简单直观的排序算法&#xff0c;其工作原理类似于人们整理一手扑克牌。插入排序通过构建有序序列&#xff0c;对于未排序数据&#xff0c;在已排序序列中从后向前扫描&#xff0c;找到相应位置并插入…

Javaweb03-Servlet技术1(Servlet,ServletConfig,ServletContext)

Servlet技术(Servlet,ServletConfig,ServletContext) 1.Servlet的概述 Servlet是运行在Web服务器端的Java应用程序&#xff0c;它使用Java语言编写。与Java程序的区别是&#xff0c;Servlet 对象主要封装了对HTTP请求的处理&#xff0c;并且它的运行需要Servlet容器(Tomcat)的…

MySQL与PostgreSQL关键对比四(关联查询性能)

引言&#xff1a;MySQL单表的数据规模一般建议在百万级别&#xff0c;而PostgreSQL的单表级别一般可以到亿级&#xff0c;如果是MPP版本就会更多。从基础数据建议上&#xff0c;不难看出&#xff0c;MySQL在Join的情况下也就是主要查询的情况下性能和PostgreSQL相差还是很大的。…

Navicat和SQLynx产品功能比较一(整体比较)

Navicat和SQLynx都是数据库管理工具&#xff0c;在过去的二十年中&#xff0c;国内用户主要是使用Navicat偏多&#xff0c;一般是个人简单开发需要&#xff0c;数据量一般不大&#xff0c;开发相对简单。SQLynx是最近几年的数据库管理工具&#xff0c;Web开发&#xff0c;桌面版…

【odoo】odoo中对子数据的独有操作[(0, 0, {‘name‘: ‘demo‘})]

概要 在Odoo中&#xff0c;有种写法用于操作 one2many 或 many2many 字段时&#xff0c;描述如何在数据库中创建、更新或删除相关记录。具体而言&#xff0c;这是一种命令格式&#xff0c;被称为 "commands" 或 "special command tuples"&#xff0c;用于 …

高考志愿填报,大学读什么专业比较好?

高考分数出炉后&#xff0c;选择什么样的专业&#xff0c;如何去选择专业&#xff1f;于毕业生而言是一个难题。因为&#xff0c;就读的专业前景不好&#xff0c;意味着就业情况不乐观&#xff0c;意味着毕业就是失业。 盲目选择专业的确会让自己就业时受挫&#xff0c;也因此…

服务器数据恢复—OceanStor存储中NAS卷数据丢失如何恢复数据?

服务器存储数据恢复环境&故障&#xff1a; 华为OceanStor某型号存储。工作人员在上传数据时发现该存储上一个NAS卷数据丢失&#xff0c;管理员随即关闭系统应用&#xff0c;停止上传数据。这个丢失数据的卷中主要数据类型为office文件、PDF文档、图片文件&#xff08;JPG、…

Hbase搭建教程

Hbase搭建教程 期待您的关注 ☀小白的Hbase学习笔记 目录 Hbase搭建教程 1.上传hbase的jar包并解压 2.重新登录 3.启动zookeeper 4.配置环境变量 5.关闭ZK的默认配置 6.修改hbase-site.xml文件 7.修改regionservers文件 8.将配置好的文件分发给其它节点 9.配置环境变量…

Vue34-销毁流程

一、销毁流程预览 二、vm.$destroy()函数的调用&#xff0c;开始销毁流程 一个应用只有一个vm&#xff0c;但是一个vm会管理一堆组件实例对象&#xff08;和vm很像&#xff1a;微型的vm&#xff09;。 销毁流程中解绑的事件监听器&#xff0c;是自定义事件&#xff0c;不是原…

大白菜PE系统进入时一直 ACPI_BIOS_ERROR

安装系统PE不支持&#xff0c;主板不兼容&#xff0c;换个WIN10的PE就解决了&#xff0c;跟之前部分电脑需要WIN8的PE同理 WIN10PE教程 WIN8PE教程

面试题:Redis是什么?有什么作用?怎么测试?

有些测试朋友来问我&#xff0c;redis要怎么测试&#xff1f;首先我们需要知道&#xff0c;redis是什么&#xff1f;它能做什么&#xff1f; redis是一个key-value类型的高速存储数据库。 redis常被用做&#xff1a;缓存、队列、发布订阅等。 所以&#xff0c;“redis要怎么测试…

AI时代新爬虫:网站自动转LLM数据,firecrawl深度玩法解读

在大模型的时代&#xff0c;爬虫技术也有了很多新的发展&#xff0c;最近出现了专门针对大模型来提取网站信息的爬虫&#xff0c;一键将网页内容转换为LLM-ready的数据。今天我们介绍其中的开源热门代表&#xff1a;firecrawl。 firecrawl 是什么 FireCrawl是一款创新的爬虫工…

文件初阶入门(葵花宝典)

1. 文件的顺序读写 1.1 顺序读写函数的介绍 函数名 功能 适用于 fgetc 字符输入函数 所有输入流 fputc 字符输出函数 所有输出流 fgets 文本行输入函数 所有输入流 fputs 文本行输出函数 所有输出流 f…

hrm人力管理系统源码(从招聘到薪酬的全过程人力管控系统)

一、项目介绍 一款全源码可二开&#xff0c;可基于云部署、私有部署的企业级数字化人力资源管理系统&#xff0c;涵盖了招聘、人事、考勤、绩效、社保、酬薪六大模块&#xff0c;解决了从人事招聘到酬薪计算的全周期人力资源管理&#xff0c;符合当下大中小型企业组织架构管理运…

【FPGA】静态分析与时序约束(持续更新

Reference&#xff1a; V2静态时序分析与时序约束文档 入门 无时序约束场景中&#xff0c;普通图像显示不清晰&#xff0c;千兆网口接收Ethernet package 数据不正常&#xff0c;红外场景中图像显示不正常 Definition&#xff1a; 我们提出一些特定的时序要求&#xff08;或…

Application Studio 学习笔记(2)

一、rest-erp 1、设置需要调用的BO服务名和BO方法名 2、设定BO方法的参数 方法的参数名已经自动获取&#xff0c;常规类型的参数取值直接在Method Parameters中设定 DataSet类型的参数取值&#xff0c;需要在Request Parameters中设定 设置Parameter Path为DataSet参数名&…

安川机器人MA1440减速机维修方法

一、安川机械臂减速器维修方法 1. 齿轮磨损维修 对于轻微磨损的齿轮&#xff0c;可以通过重新调整啮合间隙来恢复性能。对于严重磨损的齿轮&#xff0c;需要更换新安川MA1440机械手齿轮箱齿轮。 2. 轴承损坏维修 对于损坏的轴承&#xff0c;需要更换新的轴承。在更换过程中&…

【LLM之RAG】Adaptive-RAG论文阅读笔记

研究背景 文章介绍了大型语言模型&#xff08;LLMs&#xff09;在处理各种复杂查询时的挑战&#xff0c;特别是在不同复杂性的查询处理上可能导致不必要的计算开销或处理不足的问题。为了解决这一问题&#xff0c;文章提出了一种自适应的查询处理框架&#xff0c;动态选择最合…

【文心智能体分享】日记周报助手

引言 在繁忙的实习生活中&#xff0c;你是否曾为如何整理日常的工作日志、周报、月报而烦恼&#xff1f;现在&#xff0c;我们为你带来了一个全新的智能体——“日记周报助手”&#xff0c;它将成为你实习过程中的得力助手&#xff0c;帮你轻松整理实习日志&#xff0c;让你的…