Define Entities and Repositories in Micronaut

In the previous post, we successfully created a Micronaut project and configured it to connect with H2, PostgreSQL, and MySQL databases.

You can check that out – Setting Up a Micronaut App with H2 / PostgreSQL / MySQL

Now it’s time to define:

  • Entities β€” Java classes that map to database tables.
  • Repositories β€” Interfaces that handle database operations (CRUD).

Micronaut Data makes this process extremely simple and type-safe, with compile-time query generation.

Define Entities and Repositories in Micronaut

πŸ”‘ What are Entities?

Entities represent database tables. Each entity is a simple Java class annotated with @Entity. Every field represents a column in the table.

Micronaut Data supports both JPA annotations and its own Data annotations.

In our school management example, let’s create an entity for Student.

πŸ— Directory Structure

We will organize the code under:

Creating the Student Entity

Let’s create our first entity under the entities package.

File: com/kscodes/micronaut/school/entities/Student.java

πŸ” Explanation:

  • @MappedEntity("students") β€” Maps to students table.
  • @Id β€” Marks primary key.
  • @GeneratedValue β€” Auto-generates ID.
  • @Column(nullable = false) β€” Ensures name cannot be null.
  • Fields like dateOfBirth and email are optional.

πŸ”‘ What are Repositories?

Repositories are interfaces where you declare database operations.
Micronaut generates the full implementation at compile time.
No need to write SQL or boilerplate code!

πŸ”§ Creating the Student Repository

Let’s create a repository interface under repositories package.

File: com/kscodes/micronaut/school/repositories/StudentRepository.java

πŸ” Explanation:

  • @Repository β€” Marks this as a Micronaut Data repository.
  • CrudRepository<Student, Long> β€” Provides all basic CRUD methods:
    • save()
    • findById()
    • findAll()
    • deleteById()

πŸ”₯ Finder Methods

Micronaut Data allows you to define custom queries by just writing method names!

Example: Find students by name

You don’t need to write any query!
Micronaut will automatically generate this at compile time.

πŸ”§ Table Creation

If you’re using H2 or PostgreSQL/MySQL with Flyway or Liquibase (covered in a later post), tables can be automatically created based on entities or migrations.

For testing with H2, Micronaut can auto-create tables:

⚠ For production, always use migrations instead of auto-DDL.

βœ… Quick Test with Service Layer

You can now inject the repository in your services:

🐞 Common Issues

ProblemSolution
“Table not found”Ensure database schema is created
“Cannot find repository bean”Check correct package scanning
“NullPointerException”Verify DI is properly configured

🌐 External References