Simple Spring Boot Application end-2-end

Spring Boot is a popular Java framework for building web applications. One of the key components of any Spring Boot application is the controller, which is responsible for handling incoming requests and returning responses to clients. In this article, we’ll explore how to use Spring Boot controllers to perform CRUD (Create, Read, Update, Delete) operations.

Setting Up the Project

To get started, we’ll need to set up a Spring Boot project. We can do this by creating a new Maven project and adding the following dependencies to the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

The spring-boot-starter-web dependency provides the necessary classes for building web applications, while the spring-boot-starter-data-jpa dependency provides support for data persistence using the Java Persistence API (JPA). Finally, the h2 dependency provides an in-memory database that we can use for testing purposes.

Creating the Model

Next, we’ll create a simple model class that represents an entity in our application. We’ll call this class Product and it will have the following properties:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private double price;

    // getters and setters
}

This class is annotated with @Entity, which tells JPA to treat it as an entity in the database. The @Id and @GeneratedValue annotations specify that the id property should be the primary key for this entity, and that its value should be generated automatically by the database.

Creating the Repository

Next, we’ll create a repository interface that extends the JpaRepository interface provided by Spring Data JPA. This interface will provide us with the basic CRUD operations for our Product entity.

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

With this interface in place, we can use it to perform CRUD operations on our Product entity.

Creating the Controller

Now, we’ll create a controller that will handle incoming requests and perform CRUD operations on our Product entity. We’ll call this class ProductController and it will have the following methods:

@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping("/")
public List<Product> getAllProducts() {
    return productRepository.findAll();
}

@GetMapping("/{id}")
public Product getProductById(@PathVariable("id") Long id) {
    return productRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Product not found"));
}

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

@PutMapping("/{id}")
public Product updateProduct(@PathVariable("id") Long id, @RequestBody Product productData) {
    Product product = productRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Product not found"));

    product.setName(productData.getName());
    product.setPrice(productData.getPrice());

    return productRepository.save(product);
}

@Delete
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteProduct(@PathVariable("id") Long id) {
    Product product = productRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Product not found"));

    productRepository.delete(product);

    return ResponseEntity.ok().build();
}
}

This class is annotated with @RestController, which tells Spring that this class will handle incoming requests and return responses. The @RequestMapping annotation specifies that this controller will handle requests with the /api/products prefix.

We’ve also injected an instance of the ProductRepository interface using the @Autowired annotation. This will allow us to perform CRUD operations on our Product entity.

The getAllProducts() method returns a list of all Product entities in the database. The getProductById() method retrieves a single Product entity by its ID. The createProduct() method creates a new Product entity. The updateProduct() method updates an existing Product entity. Finally, the deleteProduct() method deletes an existing Product entity.

Testing the Application

With our controller in place, we can test our application by sending HTTP requests to it. We can use a tool like Postman to send requests to our endpoints.

To retrieve all products, we can send a GET request to http://localhost:8080/api/products/.

To retrieve a single product by ID, we can send a GET request to http://localhost:8080/api/products/{id}, where {id} is the ID of the product we want to retrieve.

To create a new product, we can send a POST request to http://localhost:8080/api/products/ with a JSON payload containing the name and price properties of the new product.

To update an existing product, we can send a PUT request to http://localhost:8080/api/products/{id} with a JSON payload containing the updated name and price properties of the product.

To delete an existing product, we can send a DELETE request to http://localhost:8080/api/products/{id}.

Conclusion

In this article, we’ve explored how to use Spring Boot controllers to perform CRUD operations. We’ve created a simple Product entity, a repository interface, and a controller with methods for handling GET, POST, PUT, and DELETE requests. We’ve also seen how to test our application by sending HTTP requests to our endpoints.

By using Spring Boot controllers, we can easily create RESTful APIs that perform CRUD operations on our database entities. With the help of Spring Data JPA and the Spring Boot framework, we can focus on writing business logic rather than worrying about low-level database operations.

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x