Master GraphQL with Spring Boot 3: Full-Stack API Guide
Learn how to set up a Spring Boot 3.0.9 environment, define entities, repositories, services, and a GraphQL schema, then expose a GraphQL endpoint with sample queries, illustrating complete backend API development using GraphQL and JPA.
Overview
GraphQL is both a query language for APIs and a runtime that provides a clear, type‑based description of your data, allowing clients to request exactly the fields they need without over‑fetching. It enables fetching multiple related resources in a single request and evolves easily over time.
Environment Configuration
Use Spring Boot 3.0.9 with the following Maven 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>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>Application properties (application.yml) should configure the datasource, JPA, and GraphQL endpoint:
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
jpa:
generateDdl: false
hibernate:
ddlAuto: update
openInView: true
show-sql: true
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: trueEnabling spring.graphql.graphql.enabled=true provides a UI for testing queries.
Entity Definitions
Define JPA entities for Book and Author:
@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<>();
}
@Entity
@Table(name = "t_author")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
// foreign key to Book
private Long bid;
}Repository Definitions
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {}
public interface AuthorRepository extends JpaRepository<Author, Long>, JpaSpecificationExecutor<Author> {
List<Author> findByBid(Long bid);
}Service Definition
@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
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
}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);
}
}Testing the API
Access the GraphQL endpoint (default http://localhost:8080/graphql) and send queries such as:
Only the requested fields are returned, e.g., querying just book information or selecting specific fields.
Clients fully control which fields to retrieve, making the API flexible and efficient.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
