Skip to main content

Spring Boot CRUD REST API in 30 Minutes: JPA + H2, Step by Step (With Source Code)

This is the written version of the most-watched video on my channel: a complete CRUD REST API in Spring Boot, built in about 30 minutes. It has crossed 100,000 views, and the comments under it have taught me exactly where beginners get stuck, so this post covers the code and also every error people have reported to me since.

Every code block below is copied from the project on GitHub. The app manages a list of books: you can add a book, read one or all of them, update one, and delete one or all. It uses Spring Web for the REST endpoints, Spring Data JPA for the database code, and H2, an in-memory database, so there is nothing to install apart from Java.

What you'll build

Four Java files and one properties file. Each has one job:

FileIts one job
Book.javaThe entity: one Java class that maps to one table, Books.
BookRepository.javaThe data access layer. You write an empty interface and Spring Data JPA writes the SQL.
BookController.javaThe REST API: six endpoints under /api.
application.propertiesPort, database connection, and the H2 console.
SimplestCrudExampleApplication.javaThe main method that starts everything.

These are the six endpoints, exactly as they are in the controller. The app runs on port 9090, so every URL starts with http://localhost:9090.

MethodURLWhat it doesSuccess status
GET/api/getAllBooksReturns every book200 (204 if there are none)
GET/api/getBookById/{id}Returns one book200 (404 if not found)
POST/api/addBookSaves a new book201
POST/api/updateBook/{id}Changes a book's title and author201 (404 if not found)
DELETE/api/deleteBookById/{id}Deletes one book200
DELETE/api/deleteAllBooksDeletes every book204

Step 1: Create the project

Go to start.spring.io, choose Maven and Java, and add five dependencies: Spring Web, Spring Data JPA, H2 Database, Lombok and Spring Boot DevTools. Generate the project, unzip it and open it in IntelliJ or Eclipse. The video uses Spring Boot 2.7 with Java 17, and these are the dependencies it ends up with in pom.xml:

pom.xml
<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

Notice the runtime scope on H2. Your code never imports an H2 class; Spring Boot only needs the driver on the classpath when the app runs. If you remove this dependency, or Maven hasn't downloaded it yet, startup fails with Cannot load driver class: org.h2.Driver. That is the single most common error in the comments, and the fix is always the same: make sure this dependency is in your pom.xml, then reload the Maven project in your IDE.

Step 2: Configure the database

application.properties
server.port=9090

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update
spring.h2.console.enabled=true
# default path: h2-console
spring.h2.console.path=/h2-ui
  • server.port=9090 moves the app off the default 8080, which is often already taken.
  • jdbc:h2:mem:testdb is an in-memory database called testdb. It lives in RAM, so all data is lost when the app stops. That's ideal for learning; you'll swap it for MySQL or PostgreSQL later.
  • spring.jpa.show-sql=true prints every SQL statement Hibernate runs to the console. Keep it on while learning; it shows you what JPA is doing for you.
  • ddl-auto=update lets Hibernate create the Books table from your entity class. You never write a CREATE TABLE.
  • The last two lines switch on the H2 web console and move it from the default /h2-console to /h2-ui.
Can't see your data in the H2 console? Open http://localhost:9090/h2-ui (not /h2-console, because this project changes the path). On the login screen, set the JDBC URL to jdbc:h2:mem:testdb, user sa and an empty password. If the URL there is anything else, H2 opens a different, empty database and your table seems to be missing. Also remember the data only exists while the app is running, and only after you've added a book.

Step 3: The entity

Book.java
package com.example.SimplestCRUDExample.model;

import lombok.*;

import javax.persistence.*;

@Entity
@Table(name="Books")
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class Book {

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

    @Column
    private String title;

    @Column
    private String author;

}

@Entity tells JPA this class is a table, and @Table(name="Books") names it. @Id with @GeneratedValue means you never send an id yourself; the database assigns one. Each @Column field becomes a column.

The five Lombok annotations generate the no-argument constructor JPA needs, an all-arguments constructor, getters, setters and toString(). That saves about 40 lines, but it causes the second most common error: book.getTitle() shows up red in the controller even though the class has @Getter. That means your IDE isn't running Lombok's annotation processor. In IntelliJ, install the Lombok plugin and turn on Settings → Build → Compiler → Annotation Processors → Enable annotation processing. In Eclipse, run the Lombok jar once to install it into the IDE, then restart. If you'd rather not use Lombok at all, delete the annotations and generate the getters and setters with your IDE.

On Spring Boot 3? The import is jakarta.persistence.*, not javax.persistence.*. Spring Boot 3 moved to Jakarta EE 9+, so code written for Boot 2.x, like this video, needs that one-line change, and Boot 3 also needs Java 17 or newer. I made a separate video on upgrading: Upgrade Spring Boot 2 to Spring Boot 3.

Step 4: The repository

BookRepository.java
package com.example.SimplestCRUDExample.repo;

import com.example.SimplestCRUDExample.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

}

That empty interface is the whole data access layer. By extending JpaRepository<Book, Long>, which means "books, with Long ids", you inherit save(), findById(), findAll(), deleteById(), deleteAll(), count() and more. Spring Data generates the implementation when the app starts.

You can also add your own queries just by naming a method. A viewer asked how to search by author when one author has several books. The answer is a derived query that returns a list:

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthor(String author);

}

Spring reads the method name, sees findBy + Author, and generates select ... from books where author = ?. Return List<Book>, not Book: if the return type is a single object and two rows match, Spring throws IncorrectResultSizeDataAccessException.

Step 5: The controller

@RestController turns every return value into JSON, and @RequestMapping("/api") prefixes every URL in the class. The repository is injected with @Autowired. Let's go through the endpoints one at a time.

Read all books

@GetMapping("/getAllBooks")
public ResponseEntity<List<Book>> getAllBooks() {
    try {
        List<Book> bookList = new ArrayList<>();
        bookRepository.findAll().forEach(bookList::add);

        if (bookList.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity<>(bookList, HttpStatus.OK);
    } catch(Exception ex) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

It returns 204 No Content when the table is empty, rather than 200 with an empty list. Both are valid REST; just be consistent across your API.

Read one book

@GetMapping("/getBookById/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
    Optional<Book> bookObj = bookRepository.findById(id);
    if (bookObj.isPresent()) {
        return new ResponseEntity<>(bookObj.get(), HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

findById returns an Optional<Book> because the id might not exist. If you get the compile error The type Optional is not generic; it cannot be parameterized with arguments, your file is importing a different Optional, or your project has its own class called Optional. The import must be java.util.Optional.

Create a book

@PostMapping("/addBook")
public ResponseEntity<Book> addBook(@RequestBody Book book) {
    try {
        Book bookObj = bookRepository.save(book);
        return new ResponseEntity<>(bookObj, HttpStatus.CREATED);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

@RequestBody turns the JSON you send into a Book object. save() inserts it and returns the saved copy with its new id, which is sent back with 201 Created.

Update a book

@PostMapping("/updateBook/{id}")
public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
    try {
        Optional<Book> bookData = bookRepository.findById(id);
        if (bookData.isPresent()) {
            Book updatedBookData = bookData.get();
            updatedBookData.setTitle(book.getTitle());
            updatedBookData.setAuthor(book.getAuthor());

            Book bookObj = bookRepository.save(updatedBookData);
            return new ResponseEntity<>(bookObj, HttpStatus.CREATED);
        }

        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Load the existing row, copy the new values onto it, and save it. Because the object already has an id, save() runs an UPDATE instead of an INSERT; you can see that in the console thanks to show-sql.

Delete one book, or all of them

@DeleteMapping("/deleteBookById/{id}")
public ResponseEntity<HttpStatus> deleteBook(@PathVariable Long id) {
    try {
        bookRepository.deleteById(id);
        return new ResponseEntity<>(HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
@DeleteMapping("/deleteAllBooks")
public ResponseEntity<HttpStatus> deleteAllBooks() {
    try {
        bookRepository.deleteAll();
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

One thing to know: on Spring Boot 2.x, calling deleteById with an id that doesn't exist throws EmptyResultDataAccessException, so this endpoint returns 500. Spring Data 3 (Spring Boot 3) changed that, and a missing id is now silently ignored.

Step 6: Test it

Run SimplestCrudExampleApplication and wait for Tomcat started on port(s): 9090 in the console. I use Postman in the video; here are the same requests with curl so you can copy them.

# Create two books
curl -X POST http://localhost:9090/api/addBook \
     -H "Content-Type: application/json" \
     -d '{"title": "Clean Code", "author": "Robert C. Martin"}'

curl -X POST http://localhost:9090/api/addBook \
     -H "Content-Type: application/json" \
     -d '{"title": "Effective Java", "author": "Joshua Bloch"}'

# Read them back
curl http://localhost:9090/api/getAllBooks
curl http://localhost:9090/api/getBookById/1

# Change book 1
curl -X POST http://localhost:9090/api/updateBook/1 \
     -H "Content-Type: application/json" \
     -d '{"title": "Clean Code (2nd look)", "author": "Robert C. Martin"}'

# Delete book 2, then everything
curl -X DELETE http://localhost:9090/api/deleteBookById/2
curl -X DELETE http://localhost:9090/api/deleteAllBooks

In Postman, choose the method, paste the URL, and for POST requests pick Body → raw → JSON. If you forget that last step, Postman sends plain text and Spring answers 415 Unsupported Media Type.

Errors viewers hit most, and the fixes

ErrorCauseFix
Cannot load driver class: org.h2.DriverH2 isn't on the classpathAdd the com.h2database:h2 dependency and reload Maven
getTitle() / getAuthor() not foundLombok isn't processed by the IDEInstall the Lombok plugin and enable annotation processing
The type Optional is not genericWrong Optional importUse java.util.Optional
Table missing in the H2 consoleWrong console path or JDBC URLOpen /h2-ui and use jdbc:h2:mem:testdb
415 Unsupported Media TypeBody not sent as JSONSet the body to raw → JSON in Postman
Port 9090 was already in useAnother app (or an old run) holds the portStop the old run, or change server.port

How I'd write it today

This video was made to be the simplest possible starting point, and two comments rightly pointed out what a production API does differently. Once the basic version works, these are the two changes worth making.

Use nouns in URLs and let the HTTP method be the verb. Instead of /getAllBooks, /addBook and /updateBook/{id}, a RESTful API exposes one resource, /api/books, and the method says what to do:

@RestController
@RequestMapping("/api/books")
public class BookController {

    private final BookRepository bookRepository;

    public BookController(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    @GetMapping                                   // GET    /api/books
    public List<Book> getAll() {
        return bookRepository.findAll();
    }

    @GetMapping("/{id}")                          // GET    /api/books/1
    public ResponseEntity<Book> getById(@PathVariable Long id) {
        return bookRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping                                  // POST   /api/books
    public ResponseEntity<Book> create(@RequestBody Book book) {
        return ResponseEntity.status(HttpStatus.CREATED).body(bookRepository.save(book));
    }

    @PutMapping("/{id}")                          // PUT    /api/books/1
    public ResponseEntity<Book> update(@PathVariable Long id, @RequestBody Book book) {
        return bookRepository.findById(id).map(existing -> {
            existing.setTitle(book.getTitle());
            existing.setAuthor(book.getAuthor());
            return ResponseEntity.ok(bookRepository.save(existing));
        }).orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")                       // DELETE /api/books/1
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        if (!bookRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        bookRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

Updates now use PUT and return 200 OK, because nothing new was created; deleting a missing id returns a clean 404 instead of a 500; and the repository comes in through the constructor instead of @Autowired on a field, which makes the class easier to test.

Move the logic into a service layer. Here the controller talks to the repository directly, which is fine for a 30-minute demo. In real projects I keep controllers thin: the controller handles HTTP, a @Service class holds the business rules, and the repository only talks to the database. My ToDo application project uses that Controller → Service → Repository structure.

Source code and what to build next

The full project is on GitHub: github.com/sprashantofficial/SimplestCRUDExample. If something doesn't work, leave a comment on the video with the step you were on and the first error line from your console, and I'll reply.

Once this works, pick your next project from my Spring Boot Projects for Beginners playlist: a ToDo app with JSP, a full ecommerce store with Thymeleaf, and a library management system, each built from scratch.

Comments