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:
<code><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></code>Application properties (application.yml) should configure the datasource, JPA, and GraphQL endpoint:
<code>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: true</code>Enabling spring.graphql.graphql.enabled=true provides a UI for testing queries.
Entity Definitions
Define JPA entities for Book and Author :
<code>@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;
}</code>Repository Definitions
<code>public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {}
public interface AuthorRepository extends JpaRepository<Author, Long>, JpaSpecificationExecutor<Author> {
List<Author> findByBid(Long bid);
}</code>Service Definition
<code>@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;
}
}</code>GraphQL Schema
<code>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
}</code>Controller
<code>@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);
}
}</code>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.
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.