Creating a Simple CRUD API with Spring Boot and In-Memory Database

Below is a step-by-step guide to create a simple CRUD API using Spring Boot and an in-memory database like H2. We will use Maven to manage the project’s dependencies.

1. Set Up Your Maven Project

Create a new Maven project or directory for the Spring Boot application.

pom.xml

Here is the file with the necessary dependencies: pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>crud-api</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Spring Boot CRUD API</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>21</java.version>
    </properties>

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Starter JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- H2 Database (In-memory database) -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- Lombok for simplicity -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Maven Spring Boot plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. Create the Application Entry Point

src/main/java/org/kodejava/crudapi/CrudApiApplication.java

Create the main class for your Spring Boot application.

package org.kodejava.crudapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CrudApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrudApiApplication.class, args);
    }
}

3. Define the Entity

Create a User entity to model your data.

src/main/java/org/kodejava/crudapi/model/User.java

package org.kodejava.crudapi.model;

import jakarta.persistence.*;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;
}

4. Create the Repository

The repository will handle database operations.

src/main/java/org/kodejava/crudapi/repository/UserRepository.java

package org.kodejava.crudapi.repository;

import com.example.crudapi.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

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

5. Define the Service

The service layer will handle business logic.

src/main/java/org/kodejava/crudapi/service/UserService.java

package org.kodejava.crudapi.service;

import com.example.crudapi.model.User;
import com.example.crudapi.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

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

    public User getUserById(Long id) {
        return userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
    }

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

    public User updateUser(Long id, User user) {
        User existingUser = getUserById(id);
        existingUser.setName(user.getName());
        existingUser.setEmail(user.getEmail());
        return userRepository.save(existingUser);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

6. Create the Controller

The controller defines API endpoints for CRUD operations.

src/main/java/org/kodejava/crudapi/controller/UserController.java

package org.kodejava.crudapi.controller;

import com.example.crudapi.model.User;
import com.example.crudapi.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id));
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(user));
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        return ResponseEntity.ok(userService.updateUser(id, user));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}

7. Configure Application Properties

Configure the H2 database in . application.properties

src/main/resources/application.properties

# H2 In-Memory Database Settings
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

8. Test the Application

Run your Spring Boot application and test the REST APIs using tools like Postman or curl.

  • To get all users:
  GET http://localhost:8080/api/users
  • To get a user by ID:
  GET http://localhost:8080/api/users/{id}
  • To create a user:
  POST http://localhost:8080/api/users
  Content-Type: application/json
  {
      "name": "John Doe",
      "email": "[email protected]"
  }
  • To update a user:
  PUT http://localhost:8080/api/users/{id}
  Content-Type: application/json
  {
      "name": "Jane Doe",
      "email": "[email protected]"
  }
  • To delete a user:
  DELETE http://localhost:8080/api/users/{id}

9. Access the H2 Console

You can access the H2 database console at http://localhost:8080/h2-console.

  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa
  • Password: password

That’s it! You now have a fully functional CRUD API with Spring Boot and an in-memory H2 database.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.