How to Build a Micronaut REST API With Data and PostgreSQL
Build a Micronaut REST API backed by PostgreSQL with Micronaut Data JDBC, repositories generated at compile time, pagination and Flyway migrations.

Micronaut Data is the persistence layer that matches Micronaut's compile-time model: a repository is an interface, and the annotation processor writes its implementation while the project compiles. There is no runtime proxy and no query parsing at startup, so a misspelled property in a derived query fails the build and not the first request. This guide builds a product API on PostgreSQL with Micronaut Data JDBC and Micronaut 4. It continues from the Micronaut tutorial, and the design choices about the API itself are in REST API design rules.
Step 1: dependencies and configuration
Micronaut Launch generates these when you pick the data-jdbc, postgres and flyway features:
<dependency>
<groupId>io.micronaut.data</groupId>
<artifactId>micronaut-data-jdbc</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut.sql</groupId>
<artifactId>micronaut-jdbc-hikari</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.micronaut.flyway</groupId>
<artifactId>micronaut-flyway</artifactId>
</dependency>The processor artifact micronaut-data-processor belongs on the annotation processor path, not the classpath. Forgetting it is the usual reason a repository interface compiles and then fails at startup with a missing bean. Then configure the datasource:
datasources:
default:
url: jdbc:postgresql://localhost:5432/shop
username: shop
password: ${DB_PASSWORD:change-me}
driver-class-name: org.postgresql.Driver
flyway:
datasources:
default:
enabled: trueThe ${DB_PASSWORD:change-me} form reads an environment variable and falls back to a placeholder, so the secret never lands in the repository.
Step 2: the schema is a migration
create table product (
id bigserial primary key,
name varchar(200) not null,
price_cents bigint not null
);Flyway applies it when the application starts. Keep the schema in migrations and leave schema-generate off outside a throwaway experiment. A generated schema has no history, so two environments drift apart without anyone noticing, and the first production deploy cannot be reproduced.
Step 3: entity and repository
package dev.javahacks.shop;
import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;
import io.micronaut.serde.annotation.Serdeable;
@MappedEntity
@Serdeable
public record Product(@Id @GeneratedValue Long id, String name, long priceCents) {}package dev.javahacks.shop;
import io.micronaut.data.annotation.Query;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.Page;
import io.micronaut.data.model.Pageable;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;
import java.util.List;
@JdbcRepository(dialect = Dialect.POSTGRES)
public interface ProductRepository extends CrudRepository<Product, Long> {
List<Product> findByNameContainsIgnoreCase(String fragment);
Page<Product> findAll(Pageable pageable);
@Query("select * from product where price_cents < :max order by price_cents")
List<Product> cheaperThan(long max);
}A JDBC entity can be a record because Micronaut Data builds it through the constructor, with no setters and no proxy. The camel-case component priceCents maps to the column price_cents through the default naming strategy. Derived methods like findByNameContainsIgnoreCase are parsed during compilation, which is where the typo protection comes from. @Query takes plain SQL with named parameters, and the processor checks the parameter names against the method signature.
Step 4: the controller
@Controller("/products")
public class ProductController {
private final ProductRepository products;
public ProductController(ProductRepository products) {
this.products = products;
}
@Get
public Page<Product> list(Pageable pageable) {
return products.findAll(pageable);
}
@Get("/{id}")
public Optional<Product> get(Long id) {
return products.findById(id);
}
@Post
@Status(HttpStatus.CREATED)
public Product create(@Body Product product) {
return products.save(product);
}
}Pageable binds from the query string, so GET /products?page=0&size=20&sort=name works with no extra code. Returning an empty Optional yields a 404, which is the right answer for a missing id. The Page result carries the total count, and producing it costs a second select count(*), so use Slice instead when the client only needs "is there a next page". Note that create accepts the id from the client too; for a real API bind to a separate request type without the id, add @Valid with constraints on it, and return a consistent error body.
A request you can run
curl -s -X POST localhost:8080/products \
-H 'Content-Type: application/json' \
-d '{"name":"Grinder","priceCents":8900}'
curl -s 'localhost:8080/products?size=5&sort=name,asc'The first call returns the saved product with its generated id. The second returns a JSON page object with content, pageable and totalSize. If the first call returns 500 with a duplicate key error, check that the sequence behind bigserial was not reset by a manual import.
Why compile time matters here
Most persistence layers discover their mistakes late. Spring Data JPA parses findByNameContainsIgnoreCase when the application context starts, so a typo such as findByNmae fails at boot, after the build and the image are already made. Micronaut Data runs the same parse inside javac, so the build stops. In a pipeline that difference is a failed compile on a developer's laptop rather than a crash loop in a staging cluster.
The second consequence is memory and startup. With no reflection and no proxy generation at runtime, a Micronaut service with a PostgreSQL repository starts in a few hundred milliseconds on the JVM, and the same code compiles to a GraalVM native image without extra reflection configuration. If startup time and footprint are why you chose Micronaut, this is the layer that keeps the promise. The cost is that the repository's behaviour is fixed at build time, so you cannot compose a query from strings at runtime without dropping to the lower-level JdbcOperations.
Handling errors and validation
A product API needs three behaviours the generated repository does not give you. An invalid body should return 400 with the field name, a missing row should return 404, and a duplicate should return 409. Annotate the controller with @Validated, put @NotBlank and @Positive on the request type, and let Micronaut's validation turn violations into a 400 with a JSON body. For the duplicate case, add a unique constraint to the migration and translate the resulting exception in an ExceptionHandler. The database stays the authority on uniqueness, because a check-then-insert in code fails under concurrent requests.
Pagination and sorting in practice
Pagination looks free and is not. Page runs a count query on every call, and on a table of ten million rows that count can cost more than the page itself. If clients scroll through results, return a Slice, which fetches one extra row to learn whether another page exists and skips the count. Sorting by a client-supplied property is also a surface to restrict: sort=name is fine, but an unindexed column turns each request into a full scan. Allow a short list of sortable properties and reject the rest with a 400.
Transactions
Each repository method runs in its own transaction. When several calls must commit together, annotate a service method with @Transactional, either jakarta.transaction.Transactional or Micronaut's own annotation. Because Micronaut applies this advice at compile time through generated subclasses, the annotated class cannot be final, and a call from one method to another in the same class does not pass through the advice.
When the JDBC flavour is the wrong choice
Micronaut Data JDBC keeps the model flat on purpose. It has no lazy loading and no persistence context, and relationships are loaded with explicit joins. If the domain is a rich object graph, the JPA flavour with Hibernate (micronaut-data-hibernate-jpa) fits better, with the trade-offs in the Hibernate guide. For reporting queries with window functions, write SQL through @Query or plain JDBC, as in the JDBC tutorial. Test the repository against a real PostgreSQL, using the approach in testing Micronaut apps, so dialect differences show up before production. Full feature lists are in the Micronaut Data guide and the Micronaut guides.


