Skip to content

Schematics

RezaNajafian edited this page Dec 8, 2025 · 1 revision

Defining Schematics

An OrmSchematic describes how a logical part of your application maps to MongoDB. It defines:

  • Which database to use
  • Which model classes belong to this schema
  • Which custom value types and enums are used
  • Optional customization for codec registries

OrmSchematic Interface

Simplified definition:

public interface OrmSchematic {

    String getDatabaseName();

    List<Class<?>> getModelClasses();

    List<Class<?>> getTypeClasses();

    List<Class<? extends Enum<?>>> getEnumClasses();

    default List<CodecRegistry> handleCodecRegistry(@NotNull List<CodecRegistry> registries) {
        return registries;
    }
}

Creating a Schematic

Example schematic for a simple blog application:

import net.clydo.mongo.OrmSchematic;
import org.bson.codecs.configuration.CodecRegistry;

import java.util.List;

public class BlogSchematic implements OrmSchematic {

    @Override
    public String getDatabaseName() {
        return "blog_db";
    }

    @Override
    public List<Class<?>> getModelClasses() {
        return List.of(
                Post.class,
                Comment.class
        );
    }

    @Override
    public List<Class<?>> getTypeClasses() {
        return List.of(
                // Custom value types, if any
        );
    }

    @Override
    public List<Class<? extends Enum<?>>> getEnumClasses() {
        return List.of(
                // Enum types used in your models
        );
    }

    @Override
    public List<CodecRegistry> handleCodecRegistry(List<CodecRegistry> registries) {
        // Optionally customize the codec registries
        return registries;
    }
}

Notes

  • getDatabaseName() decides which MongoDB database is used for this schematic.
  • getModelClasses() must include all model/entity classes you want MongoHelper to manage.
  • getTypeClasses() and getEnumClasses() support custom codecs for value types and enums.
  • handleCodecRegistry(...) lets you modify the list of codec registries before they are combined. You can inject custom codecs here if needed.

Registering Schematics

After creating a MongoHelper instance, register your schematics.

Register by Instance

MongoHelper mongoHelper = MongoHelper.create(client);

BlogSchematic blogSchematic = new BlogSchematic();
mongoHelper.register(blogSchematic);

Register by Class

MongoHelper mongoHelper = MongoHelper.create(client);

mongoHelper.register(BlogSchematic.class);

When you register a schematic, MongoHelper will:

  • Validate the schematic
  • Walk through model, type, and enum classes to build metadata
  • Create a MongoDatabase with the appropriate codec registry
  • Create indexes defined in the model metadata
  • Create and cache an OperationsGroup for each model class

If the same schematic instance is registered more than once, an IllegalStateException is thrown.

Clone this wiki locally