Search code examples
javamicronautmicronaut-data

How to add a foreign key constraint with the annotations


I have a 2 entities ParentEntity and ChildEntity where the ChildEntity references the ParentEntity. This is a many (child) to one (parent) relationship and is defined as follows:

@MappedEntity
public record ChildEntity (
    @Id Long id,
    String name,
    @Relation(Kind.MANY_TO_ONE) ParentEntity parent)  {
}

and

@MappedEntity
public record ParentEntity (@Id Long id,  
                            String name) {
}

Micronaut Data executes the following SQL queries when creating the schema:

CREATE TABLE parent_entity (id BIGINT NOT NULL,name VARCHAR(255) NOT NULL);

CREATE TABLE child_entity (id BIGINT NOT NULL,name VARCHAR(255) NOT NULL,parent_id BIGINT NOT NULL);

I am expecting (or would like) the foreign key constraint to be added to enforce referential integrity, so that parent_id must always be of value parentEntity.id

How do I do this on the MappedEntity classes (ChildEntity, ParentEntity etc) while still using Micronaut Data JDBC? (no Hibernate or JPA etc.)


Solution

  • You need to use a database migration tool like flyway to create appropriate tables.