Spring Boot CRUD Demo – A Quick Start.

In this post, we are going to take a look at how we can get a quick start with spring boot by creating a simple CRUD operation.

1. Create the JPA entity class to work with. class Pet.

Generate a new spring boot project and create a class called Pet.

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
@Data
@Entity
@Table(name = "pet")
@NoArgsConstructor
public class Pet {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String color;

    public Pet(String name, String color) {
        this.name = name;
        this.color = color;
    }
}


   

2. Create the Pet service interface.

Create an interface called PetService with the following code as shown below. This interface defines the signatures of the methods that we will be working on within this demo so as to improve uniformity in method names across our project.

import java.util.List;
import java.util.Optional;

public interface PetService {
    Pet add(Pet pet);
    List<Pet> getPets();
    Pet update(Pet pet);
    void delete(Integer id);
    Optional<Pet> getById(Integer id) throws Exception;
}


3. Create the Service Class to Implement the Service interface.

This class will implement all the methods in our service interface.

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@AllArgsConstructor
public class PetServiceIpml implements PetService {
    private PetRepository petRepository;

    @Override
    public Pet add(Pet pet) {
        return petRepository.save(pet);
    }

    @Override
    public List<Pet> getPets() {
        return petRepository.findAll().stream().toList();
    }

    @Override
    public Pet update(Pet pet) {
        return petRepository.save(pet);
    }

    @Override
    public void delete(Integer id) {
        petRepository.deleteById(id);

    }

    @Override
    public Optional<Pet> getById(Integer id) throws Exception {
        return Optional.ofNullable(petRepository.findById(id)
                .orElseThrow(() -> new Exception("Pet not found !")));
    }
}


4. Create the Pet Repository interface.

This interface will implement the JPA Repository in order for us to get access to the free CRUD operations provided by Spring Data.

import org.springframework.data.jpa.repository.JpaRepository;

public interface PetRepository extends JpaRepository<Pet, Integer> {
}

5. Create the Pet Controller Class.

Finally, we are going to create the controller class to define all endpoints for our demo project.

import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;

@RestController
@AllArgsConstructor
@RequestMapping("/pets")
public class PetController {
    private PetService petService;

    @GetMapping("/all")
    public ResponseEntity<List<Pet>> getPets(){
        return  new ResponseEntity<>(petService.getPets(), OK);
    }
    @PostMapping("/add")
    public ResponseEntity<Pet> add(@RequestBody Pet pet){
        return new ResponseEntity<>(petService.add(pet), CREATED);
    }

    @PutMapping("/update")
    public ResponseEntity<Pet> update(@RequestBody Pet pet){
        return new ResponseEntity<>(petService.update(pet), CREATED);
    }

    @DeleteMapping("/pet/{id}")
    public void delete(@PathVariable("id") Integer id){
        petService.delete(id);
    }
    @GetMapping("/{id}")
    public ResponseEntity<Pet> getPet(@PathVariable("id") Integer id) throws Exception {
        return petService.getById(id).map(ResponseEntity :: ok)
                .orElseGet(()-> ResponseEntity.notFound().build());
    }

}


6. The application properties file.

Now, open the application properties file and paste into it the following code as shown below.

server.port=9192

spring.datasource.url=jdbc:mysql://localhost:3306/pet_db
spring.datasource.username= your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
// ( update, create, validate, drop-create) for different purposes.
spring.jpa.hibernate.ddl-auto=update   
spring.jpa.show-sql=true

7. Finally, run the project and test with Postman.

Now, before you run the application, check to make sure that you have created the ” pet_db ” in your database system.

Now, run the project, then open Postman and test the different endpoints.

Happy coding……

2 thoughts on “Spring Boot CRUD Demo – A Quick Start.

  1. Hi sir I follow your videos regularly I had a few questions and I have been trying to get in touch with you but I couldn’t find your email or any other social media … If possible please drop me a mail at waniazharfarooq@icloud.com . Thankyou

Comments are closed.