Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Data Access

Micronaut Data and Repositories

Learn Micronaut Data: entities, CrudRepository interfaces, query methods derived from names, and how SQL is generated at compile time. Runnable H2 stand-ins.

Writing JDBC by hand for every table is repetitive: open a connection, prepare a statement, loop over a ResultSet, map columns to fields. Micronaut Data removes that work. You write an interface that describes what you need, and an annotation processor generates the SQL and the mapping code while your project compiles. At run time there is no query parsing and no reflection, so it starts quickly and works well in native images.

The framework is not installed on this site, so the Micronaut Data code is read-only. The runnable programs are Java stand-ins on the H2 database that is available in the Java runner: a generic repository you write yourself, and a small translator from method names to SQL, which shows what the compile-time generator does.

Entities

An entity is a class or record that maps to a table. Micronaut Data has its own annotations (io.micronaut.data.annotation), so you do not need JPA:

Java
import io.micronaut.data.annotation.*;

@MappedEntity("book")
public record Book(
        @Id @GeneratedValue Long id,
        String title,
        String author,
        int pages) {}
  • @MappedEntity marks the type as persistent. The table name defaults to a snake-case version of the class name.
  • @Id marks the primary key; @GeneratedValue means the database assigns it.
  • Field names map to column names (publishedYear becomes published_year).
  • Use @MappedProperty("col") to rename a column, @Transient to skip a field, and @DateCreated or @DateUpdated for automatic timestamps.

If you prefer Jakarta Persistence annotations (@Entity, @Table), use the micronaut-data-hibernate-jpa module instead. Both approaches are covered later in relationships and other data stores.

Repositories

A repository is an interface. Choose a base interface depending on how much you want:

Interface Gives you
GenericRepository<E, ID> Nothing; you declare every method
CrudRepository<E, ID> save, update, findById, findAll, deleteById, count, existsById
PageableRepository<E, ID> Everything above plus findAll(Pageable)
ReactorCrudRepository<E, ID> The CRUD methods returning Reactor types
Java
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;

@JdbcRepository(dialect = Dialect.POSTGRES)
public interface BookRepository extends CrudRepository<Book, Long> {

    List<Book> findByAuthor(String author);

    Optional<Book> findByTitle(String title);

    List<Book> findByPagesGreaterThanOrderByPagesDesc(int pages);

    boolean existsByTitle(String title);

    long countByAuthor(String author);
}

There is no implementation class. The annotation processor reads each method name, builds the SQL, and writes the implementation. Inject BookRepository anywhere, like any bean:

Java
@Singleton
public class LibraryService {
    private final BookRepository books;

    public LibraryService(BookRepository books) { this.books = books; }

    public Book add(String title, String author, int pages) {
        return books.save(new Book(null, title, author, pages));
    }
}

Query methods from names

The method name is a tiny language: a verb, then By, then properties and operators.

Part Examples
Verb find, get, query, read, count, exists, delete
Property findByAuthor, findByTitleAndAuthor, findByAuthorOrTitle
Operator GreaterThan, LessThanEquals, Between, Like, StartingWith, Contains, IsNull, In
Ordering OrderByPagesDesc, OrderByAuthorAscTitleAsc
Limits findFirstByAuthor, findTop3ByOrderByPagesDesc

Because the names are checked at compile time, a typo such as findByAuthr fails the build instead of failing at run time. When a name becomes unreadable, switch to an explicit query, which is the topic of queries, pagination and projections.

From interface to SQL

You write An interface with method names.
Compiler runs The processor builds SQL and mapping code.
At run time Plain JDBC calls, no parsing.

Errors show up when you build, not in production.

1 / 2

Stand-in 1: a generic JDBC repository

Micronaut Data generates code like this for you. The version below is written by hand with reflection over a record, only so you can see the work being saved: building SQL from the entity's fields and mapping rows back to objects. It runs against in-memory H2.

Java A hand-written CrudRepository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in 2: method names to SQL

The processor in Micronaut Data parses names like findByAuthorAndPagesGreaterThanOrderByPagesDesc. The translator below handles a useful subset with a few regular expressions, so you can see that no magic is involved. The method names and the SQL it prints are the real shape of what gets generated. Press Run and then try your own names.

Java Translate finder names to SQL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real processor supports many more operators (Between, In, IsNull, Contains, IgnoreCase) and validates each property against the entity, so a misspelled property is a compile error.

Saving, updating and deleting

CrudRepository has save(entity), which inserts when the id is null and update(entity) for existing rows. With generated ids, save returns an instance with the new id filled in; records are immutable, so use the returned value, not the one you passed. deleteById, delete(entity) and deleteAll() remove rows. For partial changes without loading a row, declare an update method:

Java
@Query("UPDATE book SET pages = :pages WHERE id = :id")
void updatePages(long id, int pages);

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does Micronaut Data generate the SQL for a repository method?

    An annotation processor creates the implementation while the project compiles, which keeps start-up and memory low.
  2. 2. What does findByPagesGreaterThanOrderByPagesDesc return, in plain words?

    GreaterThan adds a > condition on pages, and OrderByPagesDesc sorts the result by pages descending.
  3. 3. You call books.save(new Book(null, "Dune", "Herbert", 412)) with a generated id. Which object has the real id?

    Records are immutable, so save returns a new instance that includes the generated id.
  4. 4. What happens if you misspell a property in a derived finder, such as findByAuthr?

    Names are checked against the entity at compile time.

Summary

  • Micronaut Data turns repository interfaces into SQL-backed implementations at compile time.
  • Annotate entities with @MappedEntity, @Id and @GeneratedValue.
  • CrudRepository provides the standard operations; PageableRepository adds paging.
  • Finder names such as findByAuthorAndPagesGreaterThan become SQL, and mistakes fail the build.
  • save inserts or returns the persisted copy with its id; use the return value.
  • For complex queries, move to explicit @Query methods.

Next: Queries, Pagination and Projections