This project demonstrates how to build a GraphQL API using Spring Boot, JPA, and MySQL.
-
Create a Spring Boot Project Use Spring Initializr and add dependencies:
spring-boot-starter-data-jpaspring-boot-starter-graphqlspring-boot-starter-webmysql-connector-j
-
Define Entities Create
UserandOrderentities with JPA annotations. -
Create Repositories
UseJpaRepositoryto manage entities:public interface UserRepository extends JpaRepository<User, Long> {} public interface OrderRepository extends JpaRepository<Order, Long> {}
-
Implement Services Add business logic in service classes like
UserService. -
Add GraphQL Controllers Use
@QueryMappingand@MutationMappingannotations inUserController. -
Define Schema
Addschema.graphqlsinsrc/main/resources:type Query { getUsers: [User] getUser(userId: ID!): User } type Mutation { createUser(name: String, email: String, password: String): User deleteUser(userId: ID!): Boolean }
-
Configure Application Enable GraphQL UI in
application.properties:spring.graphql.graphiql.enabled=true -
Run and Test
- Start the application:
mvn spring-boot:run. - Test GraphQL queries at
/graphiql.
- Start the application:
- Get All Users:
query { getUsers { userId name email } }
- Create a User:
mutation { createUser(name: "John Doe", email: "[email protected]", password: "password123") { userId name } }