Table of Contents
1.Establishing Projects with Necessary Dependencies
First, let’s make a Spring Boot project and add the required dependencies for Spring Boot with GraphQL and MySQL
steps:
- Go to Spring Initializr.
- Fill in the project meta data as shown.
Project: Maven
Language: Java
Spring Boot: 3.3.0
Group: com.techmasters
Artifact: springboot-graphql-demo
Name: springboot-graphql-demo
Description: Demo project for Spring Boot
Package name: com.techmasters.tech
Packaging: Jar
Java: 17 - Add the following dependencies:
Spring Web
MySQL Driver
Spring Boot DevTools
Spring Data JPA
Spring for GraphQL
4. Click on ‘GENERATE’ button to download the Project.
2. Opening your favorite IDE for Spring Boot with GraphQL and MySQL project.
Launch the project in your preferred IDE after downloading it.
Eclipse and IntelliJ IDEA are excellent options for Java development.
Steps:
- Unzip the downloded project.
- Open your IDE and select ” Open or Import from the File menu.
- Navigate the unzipped project and directory and open it.
3. Creation of required packages.
Organize your project by creating the necessary packages to separate concerns and keep the code maintainable.
Steps:
- In your IDE, navigate to the
src/main/java/com/techmasters/tech
directory. - Right-click on the directory and create the following packages:
i. model
ii. repository
iii. dto
iv. mapper
v. service
vi. controller
4. Creation of required classes.
Package: model
- Role.java
package com.pktech.springbootgraphqldemo1.model;
//Spring Boot with GraphQL and MySQL
import jakarta.persistence.*;
import lombok.Data;
import java.util.HashSet;
import java.util.Set;
import java.util.Set;
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name;
@ManyToMany(mappedBy = "roles")
private Set<User> users;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
- User.java
package com.pktech.springbootgraphqldemo1.model;
//Spring Boot with GraphQL and MySQL
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "user")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false, unique = true)
private String email;
private String firstName;
private String lastName;
@Column(nullable = false)
private LocalDateTime createdAt = LocalDateTime.now();
@Column(nullable = false)
private LocalDateTime updatedAt = LocalDateTime.now();
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Status status = Status.ACTIVE;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
// Getters and setters
public enum Status {
ACTIVE, INACTIVE
}
// Constructors, Getters, Setters, Equals, HashCode, ToString methods
}
Package: Repository
- RoleRepository.java
package com.pktech.springbootgraphqldemo1.repository;
//Spring Boot with GraphQL and MySQL
import com.pktech.springbootgraphqldemo1.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(String name);
}
- UserRepository.java
package com.pktech.springbootgraphqldemo1.repository;
//Spring Boot with GraphQL and MySQL
import com.pktech.springbootgraphqldemo1.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> { }
Package: Service
- UserService.java
package com.pktech.springbootgraphqldemo1.service;
//Spring Boot with GraphQL and MySQL
import com.pktech.springbootgraphqldemo1.dto.UserRequest;
import com.pktech.springbootgraphqldemo1.dto.UserResponse;
import java.util.List;
public interface UserService {
public UserResponse createUser(UserRequest userRequest);
public UserResponse updateUser(Long id, UserRequest userRequest);
public UserResponse getUserById(Long id);
public void deleteUser(Long id);
public UserResponse assignRoleToUser(Long userId, String roleName);
public List<UserResponse> getAllUsers();
}
- UserServiceImpl.java
package com.pktech.springbootgraphqldemo1.service;
import com.pktech.springbootgraphqldemo1.dto.*;
import com.pktech.springbootgraphqldemo1.mapper.UserMapper;
import com.pktech.springbootgraphqldemo1.model.Role;
import com.pktech.springbootgraphqldemo1.model.User;
import com.pktech.springbootgraphqldemo1.repository.RoleRepository;
import com.pktech.springbootgraphqldemo1.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
public UserResponse createUser(UserRequest userRequest) {
User user = UserMapper.toEntity(userRequest);
if (userRequest.getRoles() != null) {
Set<Role> roles = userRequest.getRoles().stream()
.map(roleName -> roleRepository.findByName(roleName)
.orElseThrow(() -> new RuntimeException("Role not found: " + roleName)))
.collect(Collectors.toSet());
user.setRoles(roles);
}
user = userRepository.save(user);
return UserMapper.toResponse(user);
}
public UserResponse updateUser(Long id, UserRequest userRequest) {
User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
user.setUsername(userRequest.getUsername());
user.setPassword(userRequest.getPassword());
user.setEmail(userRequest.getEmail());
user.setFirstName(userRequest.getFirstName());
user.setLastName(userRequest.getLastName());
user.setStatus(User.Status.valueOf(userRequest.getStatus().toUpperCase()));
if (userRequest.getRoles() != null) {
Set<Role> roles = userRequest.getRoles().stream()
.map(roleName -> roleRepository.findByName(roleName)
.orElseThrow(() -> new RuntimeException("Role not found: " + roleName)))
.collect(Collectors.toSet());
user.setRoles(roles);
}
user = userRepository.save(user);
return UserMapper.toResponse(user);
}
public UserResponse getUserById(Long id) {
User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
return UserMapper.toResponse(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
public UserResponse assignRoleToUser(Long userId, String roleName) {
User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found"));
Role role = roleRepository.findByName(roleName).orElseThrow(() -> new RuntimeException("Role not found: " + roleName));
user.getRoles().add(role);
user = userRepository.save(user);
return UserMapper.toResponse(user);
}
public List<UserResponse> getAllUsers() {
return userRepository.findAll().stream()
.map(UserMapper::toResponse)
.collect(Collectors.toList());
}
}
Package: dto
- UserRequest.java
package com.pktech.springbootgraphqldemo1.dto;
//Spring Boot with GraphQL and MySQL
import lombok.Data;
import java.util.Set;
@Data
public class UserRequest {
private String username;
private String password;
private String email;
private String firstName;
private String lastName;
private String status;
private Set<String> roles;
}
- UserResponse.java
package com.pktech.springbootgraphqldemo1.dto;
//Spring Boot with GraphQL and MySQL
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Set;
@Data
public class UserResponse {
private Long id;
private String username;
private String email;
private String firstName;
private String lastName;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private String status;
private Set<String> roles;
}
Package: mapper
- UserMapper.java
package com.pktech.springbootgraphqldemo1.mapper;
import com.pktech.springbootgraphqldemo1.dto.UserRequest;
import com.pktech.springbootgraphqldemo1.dto.UserResponse;
import com.pktech.springbootgraphqldemo1.model.User;
import com.pktech.springbootgraphqldemo1.model.Role;
import java.util.Set;
import java.util.stream.Collectors;
public class UserMapper {
public static User toEntity(UserRequest userRequest) {
User user = new User();
user.setUsername(userRequest.getUsername());
user.setPassword(userRequest.getPassword());
user.setEmail(userRequest.getEmail());
user.setFirstName(userRequest.getFirstName());
user.setLastName(userRequest.getLastName());
user.setStatus(User.Status.valueOf(userRequest.getStatus().toUpperCase()));
return user;
}
public static UserResponse toResponse(User user) {
UserResponse userResponse = new UserResponse();
userResponse.setId(user.getId());
userResponse.setUsername(user.getUsername());
userResponse.setEmail(user.getEmail());
userResponse.setFirstName(user.getFirstName());
userResponse.setLastName(user.getLastName());
userResponse.setCreatedAt(user.getCreatedAt());
userResponse.setUpdatedAt(user.getUpdatedAt());
userResponse.setStatus(user.getStatus().name().toLowerCase());
userResponse.setRoles(user.getRoles().stream().map(Role::getName).collect(Collectors.toSet()));
return userResponse;
}
}
Package: controller
- UserController.java
package com.techmasters.tech.controller;
//Spring Boot with GraphQL and MySQL
import com.techmasters.tech.dto.UserRequest;
import com.techmasters.tech.dto.UserResponse;
import com.techmasters.tech.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.web.bind.annotation.*;
//Spring Boot with GraphQL and MySQL
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public UserResponse createUser(@RequestBody UserRequest userRequest) {
return userService.createUser(userRequest);
}
@GetMapping("/{id}")
public UserResponse getUser(@PathVariable Long id) {
return userService.getUser(id);
}
}
5. Creation of GraphQL Schema
Create a file named schema.graphqls
in the src/main/resources/graphql
directory. Define the GraphQL schema as shown below.
File: schema.graphqls
type Query {
getUserById(id: ID!): UserResponse
getAllUsers: [UserResponse!]
}
type Mutation {
createUser(userRequest: UserRequest): UserResponse
updateUser(id: ID!, userRequest: UserRequest): UserResponse
deleteUser(id: ID!): String
assignRoleToUser(userId: ID!, roleName: String!): String
}
input UserRequest {
username: String!
password: String!
email: String!
firstName: String
lastName: String!
status: String!
roles: [String!]
}
type UserResponse {
id: ID!
username: String!
email: String!
firstName: String!
lastName: String!
createdAt: String!
updatedAt: String!
status: String!
roles: [String!]!
}
7. Configuring Database Properties
Configure the database connection properties in the src/main/resources/application.properties
file.
File: application.properties
spring.application.name=springboot-graphql-demo1
server.port=9001
spring.jpa.show-sql=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.url=jdbc:mysql://localhost:3306/user_table
8. Running the Project
Run the project and access the GraphQL endpoint in Postman.
Steps:
- Open your terminal and navigate to the project directory.
- Run the command
mvn spring-boot:run
to start the application. - Open Postman and enter the URL
http://localhost:9001/graphql
. - You can now test the GraphQL queries and mutations defined in the
schema.graphqls
file.
By following these steps, you will have a well-structured Spring Boot project with GraphQL and MySQL integration. This structure ensures a clean separation of concerns and allows for easy maintenance and scalability of your application.
If you want to download the project. Click Here: Github
Explore more:
-> Create A Login Registration and Forgot Password Form In HTML CSS and JavaScript.
-> Creating Responsive Login and Registration Form in Html CSS and JavaScript with Validations.
-> Create a Stunning Tailwind CSS Registration Form with HTML and JavaScript Validation.
-> Creating a Responsive Login and Signup Form in React.js
-> Building a Dynamic Login and Registration Form in React.js
-> Ultimate Login and Registration Form in HTML CSS and JavaScript with Flawless Validations
-> Ultimate Appointment Request Form in HTML and CSS