当前位置: 首页 > news >正文

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

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 {@Autowiredprivate 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 {@Autowiredprivate AuthorSevice authorSevice;/*** 经典 hollo graphql*/@QueryMappingpublic String hello(){return "hello graphql";}@QueryMappingpublic Author getAuthorBybookId(@Argument int bookid) {System.out.println("bookid:"+bookid);return authorSevice.queryAuthorByBookId(bookid);}@MutationMappingpublic 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: Querymutation: Mutation
}
type Mutation{
}
type Query{
}

编写books.graphql文件

extend type Query {hello:StringgetAuthorBybookId(bookid:Int): Author
}extend type Mutation {createUser(authorInput: AuthorInput):Author
}input AuthorInput {firstName: StringlastName: StringbookId: Int
}type Author {id: IntfirstName: StringlastName: StringbookId: Int
}type Book {id: Intname: StringpageCount: Stringauthor: Author
}

3.7 编写yml配置文件

spring:jpa:hibernate:use-new-id-generator-mappings: falsegraphql:graphiql:enabled: truewebsocket:path: /graphqlschema:printer:enabled: truelocations: classpath:/graphql   #test.graphql文件位置file-extensions: .graphqldatasource:url: jdbc:mysql://192.168.222.156:3306/book_api_data?useUnicode=true&characterEncoding=utf-8&useSSL=falsepassword: 123456username: 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

 测试查询功能

测试新增功能

相关文章:

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

1 安装插件 我这边使用的是IDEA&#xff0c;需要先按照Graphql插件&#xff0c;步骤如下&#xff1a; &#xff08;1&#xff09;打开插件管理 在IDEA中&#xff0c;打开主菜单&#xff0c;选择 "File" -> "Settings" (或者使用快捷键 Ctrl Alt S …...

vue3+ Element-Plus 点击勾选框往input中动态添加多个tag

实现效果&#xff1a; template&#xff1a; <!--产品白名单--><div class"con-item" v-if"current 0"><el-form-item label"平台名称"><div class"contaion" click"onclick"><!-- 生成的标签 …...

唯美仙侠手游【九幽仙域】win服务端+GM后台+详细教程

资源下载地址&#xff1a;九幽仙域搭建-...

Qt creator day2练习

使用手动连接&#xff0c;将登录框中的取消按钮使用第二种方式&#xff0c;右击转到槽&#xff0c;在该函数中&#xff0c;调用关闭函数&#xff0c;将登录按钮使用Qt4版本的连接到自定义的槽函数中&#xff0c;在槽函数中判断ui界面上输入的账号是否为“admin”&#xff0c;密…...

哪里有海量的短视频素材,以及短视频制作教程?

在当下&#xff0c;短视频已成为最火爆的内容形式之一&#xff0c;尤其是在抖音上。但很多创作者都面临一个问题&#xff1a;视频素材从哪里来&#xff1f;怎么拍摄才能吸引更多观众&#xff1f;别担心&#xff0c;今天我将为大家推荐几个宝藏网站&#xff0c;确保你素材多到用…...

文章MSM_metagenomics(三):Alpha多样性分析

欢迎大家关注全网生信学习者系列&#xff1a; WX公zhong号&#xff1a;生信学习者Xiao hong书&#xff1a;生信学习者知hu&#xff1a;生信学习者CDSN&#xff1a;生信学习者2 介绍 本教程使用基于R的函数来估计微生物群落的香农指数和丰富度&#xff0c;使用MetaPhlAn prof…...

Web前端与其他前端:深度对比与差异性剖析

Web前端与其他前端&#xff1a;深度对比与差异性剖析 在快速发展的前端技术领域&#xff0c;Web前端无疑是其中最耀眼的明星。然而&#xff0c;当我们谈论前端时&#xff0c;是否仅仅指的是Web前端&#xff1f;实际上&#xff0c;前端技术还包括了许多其他细分领域。本文将从四…...

AI 客服定制:LangChain集成订单能力

为了提高AI客服的问题解决能力&#xff0c;我们引入了LangChain自定义能力&#xff0c;并集成了订单能力。这使得AI客服可以根据用户提出的问题&#xff0c;自动调用订单接口&#xff0c;获取订单信息&#xff0c;并结合文本知识库内容进行回答。这种能力的应用&#xff0c;使得…...

【计算机毕业设计】242基于微信小程序的外卖点餐系统

&#x1f64a;作者简介&#xff1a;拥有多年开发工作经验&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的项目或者毕业设计。 代码可以私聊博主获取。&#x1f339;赠送计算机毕业设计600个选题excel文件&#xff0c;帮助大学选题。赠送开题报告模板&#xff…...

java程序监控linux服务器硬件,cpu、mem、disk等

实现 使用Oshi和Hutool工具包1、pom依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.github.oshi</groupId>&l…...

高考报志愿闲谈

当你的朋友在选择大学和专业时寻求建议&#xff0c;作为一名研究生并有高考经验的人&#xff0c;你可以提供一些有价值的见解和建议。 兴趣与职业目标&#xff1a; 首先询问他对哪些工科领域感兴趣&#xff0c;如机械工程、电子工程、计算机科学等。探讨他的职业目标。了解他将…...

面试官考我Object类中的所有方法及场景使用?我...

咦咦咦&#xff0c;各位小可爱&#xff0c;我是你们的好伙伴——bug菌&#xff0c;今天又来给大家普及Java 知识点啦&#xff0c;别躲起来啊&#xff0c;听我讲干货还不快点赞&#xff0c;赞多了我就有动力讲得更嗨啦&#xff01;所以呀&#xff0c;养成先点赞后阅读的好习惯&a…...

Web前端精通教程:深入探索与实战指南

Web前端精通教程&#xff1a;深入探索与实战指南 在数字化时代&#xff0c;Web前端技术已经成为构建优秀用户体验的基石。想要精通Web前端&#xff0c;不仅需要掌握扎实的基础知识&#xff0c;还需要具备丰富的实战经验和深入的思考。本文将从四个方面、五个方面、六个方面和七…...

四轴飞行器、无人机(STM32、NRF24L01)

一、简介 此电路由STM32为主控芯片&#xff0c;NRF24L01、MPU6050为辅,当接受到信号时&#xff0c;处理对应的指令。 二、实物图 三、部分代码 void FlightPidControl(float dt) { volatile static uint8_t statusWAITING_1; switch(status) { case WAITING_1: //等待解锁 if…...

OpenAI Assistants API:如何使用代码或无需代码创建您自己的AI助手

Its now easier than ever to create your own AI Assistant that can handle a lot of computing tasks for you. See how you can get started with the OpenAI AI Assistant API. 现在比以往任何时候都更容易创建您自己的AI助手&#xff0c;它可以为您处理许多计算任务。了…...

CentOS7 配置Nginx域名HTTPS

Configuring Nginx with HTTPS on CentOS 7 involves similar steps to the ones for Ubuntu, but with some variations in package management and service control. Here’s a step-by-step guide for CentOS 7: Prerequisites Domain Name: “www.xxx.com”Nginx Install…...

C++入门8 构造函数析构函数顺序|拷贝构造

一&#xff0c;构造函数析构函数 调用顺序 我们先来看下面的代码&#xff1a; #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstring> using namespace std; class student { public:char my_name[20];int my_id;student(int a) {my_id a;co…...

【git使用四】git分支理解与操作(详解)

目录 &#xff08;1&#xff09;理解git分支 主分支&#xff08;主线&#xff09; 功能分支 主线和分支关系 将分支合并到主分支 快速合并 非快速合并 git代码管理流程 &#xff08;2&#xff09;理解git提交对象 提交对象与commitID Git如何保存数据 示例讲解 &a…...

【docker】如何解决artalk的跨域访问问题

今天折腾halo的时候&#xff0c;发现artalk出现跨域访问报错&#xff0c;内容如下。 Access to fetch at https://artk.musnow.top/api/stat from origin https://halo.musnow.top has been blocked by CORS policy: The Access-Control-Allow-Origin header contains multipl…...

MYSQL 索引下推 45讲

刘老师群里,看到一位小友 问<MYSQL 45讲>林晓斌的回答 大意是一个组合索引 (a,b,c) 条件 a > 5 and a <10 and b123, 这样的情况下是如何? 林老师给的回答是 A>5 ,然后下推B123 小友 问 "为什么不是先 进行范围查询,然后在索引下推 b123?" 然后就…...

faster-whisper-GUI架构设计与性能优化:构建高效语音识别工作流的技术实践

faster-whisper-GUI架构设计与性能优化&#xff1a;构建高效语音识别工作流的技术实践 【免费下载链接】faster-whisper-GUI faster_whisper GUI with PySide6 项目地址: https://gitcode.com/gh_mirrors/fa/faster-whisper-GUI 在语音识别技术快速发展的今天&#xff0…...

深入解析STM32 SysTick定时器:从原理到时间片轮询实战

1. SysTick定时器的前世今生 第一次接触STM32的开发板时&#xff0c;我就被这个叫做SysTick的神秘定时器吸引了。当时我正为如何实现精确延时发愁&#xff0c;GPIO翻转测试显示软件延时误差高达30%&#xff0c;直到一位资深工程师提醒我&#xff1a;"内核里就藏着个高精度…...

拯救变砖的STM32:利用BOOT0/1组合实现三种烧录救机方案(含串口/JTAG异常处理)

STM32紧急救援指南&#xff1a;BOOT引脚组合的三种烧录方案与异常处理实战 引言&#xff1a;当STM32突然"变砖"时 深夜的实验室里&#xff0c;王工盯着眼前毫无反应的STM32开发板&#xff0c;额头渗出细密的汗珠——距离项目交付只剩12小时&#xff0c;核心控制程序却…...

小程序对商家私域运营到底有多重要?

小程序对商家私域运营到底有多重要&#xff1f;在企业持续获取客户成本不断上升的背景下&#xff0c;越来越多商家开始关注“私域运营”&#xff0c;而小程序也逐渐成为这一体系中的核心工具。小程序对商家私域运营的重要性&#xff0c;本质上体现在“用户沉淀能力与转化效率的…...

3大突破:让网课学习效率提升300%的智能方案

3大突破&#xff1a;让网课学习效率提升300%的智能方案 【免费下载链接】auto-play-course 简单好用的刷课脚本[支持平台:职教云,智慧职教,资源库] 项目地址: https://gitcode.com/gh_mirrors/hc/auto-play-course 在数字化学习普及的今天&#xff0c;职业教育学生平均每…...

在 SAP 系统中,利润中心(Profit Center)和业务范围(Business Area)都是用于内部管理报告的组织单元,但它们在设计理念、功能和应用上存在显著区别。简单来说,利润中心是更现代

在 SAP 系统中&#xff0c;利润中心&#xff08;Profit Center&#xff09;和业务范围&#xff08;Business Area&#xff09;都是用于内部管理报告的组织单元&#xff0c;但它们在设计理念、功能和应用上存在显著区别。简单来说&#xff0c;利润中心是更现代、更灵活、功能更强…...

Hunyuan-MT 7B一键部署教程:基于Git实现快速环境搭建

Hunyuan-MT 7B一键部署教程&#xff1a;基于Git实现快速环境搭建 想试试那个在国际翻译比赛里拿了30个第一的Hunyuan-MT-7B模型吗&#xff1f;你可能在网上看到过它的介绍&#xff0c;支持几十种语言&#xff0c;翻译效果据说很惊艳。但一看到“本地部署”、“环境配置”这些词…...

别再只看波形了!用Maxwell+Matlab深度分析电机空载气隙磁密的谐波极对数分布

电机电磁设计进阶&#xff1a;从Maxwell FFT到Matlab谐波极对数分析的工程实践 在电机设计领域&#xff0c;空载气隙磁密的谐波分析一直是评估电磁性能的核心手段。传统方法往往止步于波形观察和简单频谱分析&#xff0c;却忽略了谐波极对数分布这一关键维度——它直接关联着电…...

QuickSnap:Blender三维建模效率革命,快速对齐插件让精准建模变得简单

QuickSnap&#xff1a;Blender三维建模效率革命&#xff0c;快速对齐插件让精准建模变得简单 【免费下载链接】quicksnap Blender addon to quickly snap objects/vertices/points to object origins/vertices/points 项目地址: https://gitcode.com/gh_mirrors/qu/quicksnap…...

SpringBoot+Hadoop实战:手把手教你搭建民宿数据可视化平台(附完整源码)

SpringBootHadoop实战&#xff1a;构建高可用民宿数据可视化平台 1. 项目背景与技术选型 民宿行业近年来呈现爆发式增长&#xff0c;随之而来的是海量房源信息、用户评价和交易数据的积累。传统的关系型数据库在处理这类数据时面临存储瓶颈和计算性能不足的问题。我们选择Spr…...