This guide explains how to build GraphQL APIs with Spring Boot and use H2 as the backend database for testing and development.
1. Add Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2
spring.datasource.url=jdbc:h2:mem:graphql
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
3. Create Entity
@Entity
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
private String author;
}
4. Repository
public interface BookRepository extends JpaRepository<Book, Long> {}
5. Define GraphQL Schema (schema.graphqls)
type Book {
id: ID!
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String, author: String): Book
}
6. GraphQL Controller
@Controller
public class BookGraphQLController {
private final BookRepository repo;
public BookGraphQLController(BookRepository repo) {
this.repo = repo;
}
@QueryMapping
public List<Book> books() {
return repo.findAll();
}
@MutationMapping
public Book addBook(@Argument String title, @Argument String author) {
return repo.save(new Book(null, title, author));
}
}
7. Test GraphQL
Go to
/graphiql or
/graphql and run:
mutation {
addBook(title: "GraphQL Guide", author: "John Doe") {
id
title
author
}
}
query {
books {
id
title
author
}
}
image quote pre code