blog bg

November 29, 2024

Creating a Sample User and Product Service using Spring Boot

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

 

So, hi guys, my today's topic is about creating microservices that communicate easily. Your app can now have multiple services like, for users, products, or sometimes for both using Spring Boot. In this article, I'll show you how to set up user and product service with modular design. Using these services, you'll get enough experience with RESTful APIs, JPA, and in-memory databases. As understanding all these elements is important for building real-world apps. Let's start…

 

Setting up a Spring Boot Project

First of all, go to Spring Initializr and create a new Spring Boot project from there. Select the following dependencies:

  • Spring Web (to create RESTful APIs)
  • Spring Data JPA (for database interaction)
  • H2 Database (for in-memory storage to keep things simple)

After downloading these dependencies, now import your project in the IDE, you're familiar with like; IntelliJ IDEA or Eclipse. In your Spring Boot project, there will be a src folder with main and test directory. This is where you can write and test your code. After setting up this, you're all ready to create your services.

 

Creating the User Service

 

1. User Entity

For creating user service, first you've to create a class named User inside the model package. Use the @Entity annotation to mark it as a database entity. The class will be like this:

 

 

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
}

 

2. User Repository

Next, you've to create an interface named UserRepository that extends JpaRepository to make database operations simple.

 

 

public interface UserRepository extends JpaRepository<User, Long> { }

 

3. User Controller

At the end, create a UserController class with REST endpoints to manage multiple users.

 

 

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
}

 

In this code, you can perform basic CRUD operations for users using REST APIs.

 

Creating the Product Service

 

1. Product Entity

The same procedure as we discussed for user entity, create a Product class.

 

 

 

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
}

 

2. Product Repository

Define a ProductRepository interface to manage product-related data.

 

 

public interface ProductRepository extends JpaRepository<Product, Long> { }

 

3. Product Controller

In ProductController, define endpoints to create and retrieve products.

 

 

@RestController
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @GetMapping
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productRepository.save(product);
    }
}

 

Testing the Services

Once you've create your user and product services, let's test them whether they are working or not? To test your services, you can use Postman or any other API testing tool.

 

Adding a User:

Send a POST request to http://localhost:8080/users with the following JSON payload:

 

 

{
    "name": "John Doe",
    "email": "john.doe@example.com"
}

 

Adding a Product:

Send a POST request to http://localhost:8080/products with this payload:

 

 

{
    "name": "Laptop",
    "price": 1200.00
}

 

Retrieving Data:

Use GET /users and GET /products to confirm the data is stored correctly.

 

Conclusion

In this blogpost I've explained how to create basic Spring Boot User and Product services. These individual, scalable, and efficient services use microservices design principles. You can also try to add authentications or a MySQL database for permanent storage next. These modular services simplify application maintenance and expansion.

124 views

Please Login to create a Question