Learn how to get started with Graphql using spring boot framework. In this article, you will be learning like how to add the schema details and mapping the function and request payload with Graphql @QueryMapping into your controller class.
You need Spring web, JPA, Mysql, Lombok and Spring Graphql dependencies to your pom module.
schema.graphqls (This file should be created inside the resources/graphql folder)
type Query{
findAll: [User]
userById(id: ID): User
}
type User{
id: ID
name: String
gender: String
emailId: String
}
UserGQLController .java
package com.hakeemit.graphql.controller;
import com.hakeemit.graphql.entity.User;
import com.hakeemit.graphql.entity.UserDetails;
import com.hakeemit.graphql.service.UserServices;
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.stereotype.Controller;
import java.util.List;
@Controller
public class UserGQLController {
@Autowired
private UserServices userServices;
@QueryMapping
public List findAll(){
return userServices.getAllUser();
}
@QueryMapping
public User userById(@Argument int id){
return userServices.userById(id);
}
}
@QueryMapping will be the entry point just like REST API Get Mapping.
UserServices .java
package com.hakeemit.graphql.service;
import com.hakeemit.graphql.entity.User;
import com.hakeemit.graphql.entity.UserDetails;
import com.hakeemit.graphql.repositories.UserRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServices {
@Autowired
private UserRepositories userRepositories;
public User userById(int id){
Optional user = userRepositories.findById(id);
return user.get();
}
public List getAllUser(){
return userRepositories.findAll();
}
}
pom.xml add the 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>
Start running your application
Comments
Post a Comment