This guide shows how to perform
CRUD operations in a
Spring Boot project using the
H2 in-memory database for fast development.
1. Add Dependency
In
pom.xml
:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. Configure H2
application.properties
:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
3. Create Entity
import jakarta.persistence.*;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
4. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}
5. Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
private final StudentRepository repo;
public StudentController(StudentRepository repo) {
this.repo = repo;
}
@PostMapping
public Student create(@RequestBody Student student) {
return repo.save(student);
}
@GetMapping
public List<Student> getAll() {
return repo.findAll();
}
@GetMapping("/{id}")
public Student getOne(@PathVariable Long id) {
return repo.findById(id).orElse(null);
}
@PutMapping("/{id}")
public Student update(@PathVariable Long id, @RequestBody Student s) {
return repo.findById(id)
.map(st -> {
st.setName(s.getName());
st.setEmail(s.getEmail());
return repo.save(st);
}).orElse(null);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
repo.deleteById(id);
}
}
6. Test the API
Start the app:
mvn spring-boot:run
Test endpoints with
Postman or
curl:
POST /students
→ create
GET /students
→ read all
GET /students/{id}
→ read one
PUT /students/{id}
→ update
DELETE /students/{id}
→ delete
image quote pre code