AI Hints
Home›Spring Boot Tutorial›What REST Is, Returning Objects as JSON and Records for Data
Spring Boot · Lesson 21 of 120

Records for Data

Short data classes.

⏱ 2 min read▶ Video at 27:38🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Writing fields, a constructor, and getters for every data class is a lot of typing. Java records do it all in one line.

  • Fields, constructor, getters
  • A lot of typing
  • One line instead

Book as a record

This one line declares a record called Book, with four components. Java writes the private fields, and the constructor, for us. It also writes accessor methods, named id, title, author, and price. Plus equals, hash code, and a readable to string.

Book.javajava
public record Book(Integer id, String title, String author, double price) {}

Records in a nutshell

Records are immutable, so their values can't change after creation. Accessors don't start with get. It's dot title, not dot get title. Jackson understands records perfectly. That's why records are the favourite way to hold API data.

keyvalue
Immutablevalues never change
Accessorstitle(), not getTitle()
JSONJackson handles them
Use forAPI data, DTOs

Using the record

We create two books, with the constructor. Then we call the title accessor, and print a whole record. Finally, we return both books. Run it. The response is a JSON list of both books. In the app log, the accessor gives Dune. And printing a record shows all its values, with their names.

BookController.javajava
@RestController
public class BookController {

    @GetMapping("/books")
    public List<Book> books() {
        Book dune = new Book(1, "Dune", "Frank Herbert", 9.99);
        Book hobbit = new Book(2, "The Hobbit", "J.R.R. Tolkien", 8.99);
        System.out.println("dune.title() = " + dune.title());
        System.out.println(hobbit);
        return List.of(dune, hobbit);
    }
}
Output
[
  {"id":1,"title":"Dune","author":"Frank Herbert","price":9.99},
  {"id":2,"title":"The Hobbit","author":"J.R.R. Tolkien","price":8.99}
]

── app log ──
dune.title() = Dune
Book[id=2, title=The Hobbit, author=J.R.R. Tolkien, price=8.99]
Also uses Book.java
public record Book(Integer id, String title, String author, double price) {}
Also uses _curl.sh
curl localhost:8080/books

Summary

A record declares a data class in one line, with a constructor, accessors, and to string. We'll use Book records for the rest of the module. Next, creating books with POST.

Key takeaways
  • record Book(...)
  • title() accessor
  • Perfect for JSON
Next up: @PostMapping and @RequestBody — creating data